Skip to content

Commit

Permalink
Fixed generic aliases not passing checks against type (#433)
Browse files Browse the repository at this point in the history
Co-authored-by: Alex Grönholm <alex.gronholm@nextday.fi>
  • Loading branch information
fefe982 and agronholm committed Mar 23, 2024
1 parent d481a51 commit 2df6f4a
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 2 deletions.
3 changes: 3 additions & 0 deletions docs/versionhistory.rst
Expand Up @@ -11,6 +11,9 @@ This library adheres to
subscript (`#442 <https://github.com/agronholm/typeguard/issues/442>`_)
- Fixed ``TypedDict`` from ``typing_extensions`` not being recognized as one
(`#443 <https://github.com/agronholm/typeguard/issues/443>`_)
- Fixed ``typing`` types (``dict[str, int]``, ``List[str]``, etc.) not passing checks
against ``type`` or ``Type``
(`#432 <https://github.com/agronholm/typeguard/issues/432>`_, PR by Yongxin Wang)

**4.1.5** (2023-09-11)

Expand Down
7 changes: 5 additions & 2 deletions src/typeguard/_checkers.py
Expand Up @@ -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
Expand Down Expand Up @@ -440,7 +443,7 @@ def check_class(
args: tuple[Any, ...],
memo: TypeCheckMemo,
) -> None:
if not isclass(value):
if not isclass(value) and not isinstance(value, generic_alias_types):
raise TypeCheckError("is not a class")

if not args:
Expand Down Expand Up @@ -475,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)}")


Expand Down
8 changes: 8 additions & 0 deletions tests/test_checkers.py
Expand Up @@ -891,6 +891,14 @@ def test_union_typevar(self):
T = TypeVar("T", bound=Parent)
check_type(Child, Type[T])

@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], check_against)

check_type(Dict, check_against)
check_type(Dict[str, str], check_against)


class TestIO:
@pytest.mark.parametrize(
Expand Down

0 comments on commit 2df6f4a

Please sign in to comment.