From 1ee36251b290bbcbb2d66231018af889c538e38d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alex=20Gr=C3=B6nholm?= Date: Sat, 23 Mar 2024 14:34:32 +0200 Subject: [PATCH] Refined the checks and their tests --- docs/versionhistory.rst | 3 +++ src/typeguard/_checkers.py | 11 +++++------ tests/test_checkers.py | 10 ++++++---- 3 files changed, 14 insertions(+), 10 deletions(-) diff --git a/docs/versionhistory.rst b/docs/versionhistory.rst index d7b29b4..f719b7e 100644 --- a/docs/versionhistory.rst +++ b/docs/versionhistory.rst @@ -11,6 +11,9 @@ This library adheres to subscript (`#442 `_) - Fixed ``TypedDict`` from ``typing_extensions`` not being recognized as one (`#443 `_) +- Fixed parametrized types (``dict[str, int]``, ``List[str]``, etc.) not passing checks + against ``type`` or ``Type`` + (`#432 `_, PR by Yongxin Wang) **4.1.5** (2023-09-11) diff --git a/src/typeguard/_checkers.py b/src/typeguard/_checkers.py index 7826870..f79da91 100644 --- a/src/typeguard/_checkers.py +++ b/src/typeguard/_checkers.py @@ -83,6 +83,9 @@ ] checker_lookup_functions: list[TypeCheckLookupCallback] = [] +generic_alias_types: tuple[type, ...] = (type(List), type(List[Any])) +if sys.version_info >= (3, 9): + generic_alias_types += (types.GenericAlias,) # Sentinel @@ -440,11 +443,7 @@ def check_class( args: tuple[Any, ...], memo: TypeCheckMemo, ) -> None: - if not isclass(value) and not ( - (sys.version_info >= (3, 11) and isinstance(value, types.GenericAlias)) - or isinstance(value, type(Type)) - or isinstance(value, type(Type[Any])) - ): + if not isclass(value) and not isinstance(value, generic_alias_types): raise TypeCheckError("is not a class") if not args: @@ -479,7 +478,7 @@ def check_class( raise TypeCheckError( f"did not match any element in the union:\n{formatted_errors}" ) - elif not issubclass(value, expected_class): + elif not issubclass(value, expected_class): # type: ignore[arg-type] raise TypeCheckError(f"is not a subclass of {qualified_name(expected_class)}") diff --git a/tests/test_checkers.py b/tests/test_checkers.py index 262a213..f9aef31 100644 --- a/tests/test_checkers.py +++ b/tests/test_checkers.py @@ -891,11 +891,13 @@ def test_union_typevar(self): T = TypeVar("T", bound=Parent) check_type(Child, Type[T]) - def test_generic_aliase(self): + @pytest.mark.parametrize("check_against", [type, Type[Any]]) + def test_generic_aliase(self, check_against): if sys.version_info >= (3, 9): - check_type(dict[str, str], type) - check_type(Dict, Type[Any]) - check_type(Dict[str, str], Type[Any]) + check_type(dict[str, str], check_against) + + check_type(Dict, check_against) + check_type(Dict[str, str], check_against) class TestIO: