From 9bfb72b05598922cf5cc3fea233d1ebf86ba00dd Mon Sep 17 00:00:00 2001 From: Harry Dalton Date: Thu, 13 Jul 2023 13:53:36 +0100 Subject: [PATCH] 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. --- Lib/fontTools/unicodedata/__init__.py | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/Lib/fontTools/unicodedata/__init__.py b/Lib/fontTools/unicodedata/__init__.py index 019779847..808c9c722 100644 --- a/Lib/fontTools/unicodedata/__init__.py +++ b/Lib/fontTools/unicodedata/__init__.py @@ -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". """