Fix typing of script_horizontal_direction()

Without explicit annotation, some type checkers infer that the type of
the 'default' argument can only be type[KeyError]. This was the case
in unicodedata_test.py, where pyright disallowed "LTR". This commit adds
annotations to avoid this, fixing the issue in the test (and external
code dependent on the API).

Some of the other functions in this file have the same semantics and
suffer from the same type error, and so this fix could also be extended
to them as usage requires.
This commit is contained in:
Harry Dalton 2023-07-13 13:53:36 +01:00
parent d61cad65fc
commit 9bfb72b055

View File

@ -1,7 +1,11 @@
from __future__ import annotations
from fontTools.misc.textTools import byteord, tostr
import re
from bisect import bisect_right
from typing import Literal, TypeVar, overload
try:
# use unicodedata backport compatible with python2:
@ -192,7 +196,25 @@ RTL_SCRIPTS = {
}
def script_horizontal_direction(script_code, default=KeyError):
HorizDirection = Literal["RTL", "LTR"]
T = TypeVar("T")
@overload
def script_horizontal_direction(script_code: str, default: T) -> HorizDirection | T:
...
@overload
def script_horizontal_direction(
script_code: str, default: type[KeyError] = KeyError
) -> HorizDirection:
...
def script_horizontal_direction(
script_code: str, default: T | type[KeyError] = KeyError
) -> HorizDirection | T:
"""Return "RTL" for scripts that contain right-to-left characters
according to the Bidi_Class property. Otherwise return "LTR".
"""