Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed generic aliases not passing checks against type #433

Merged
merged 7 commits into from
Mar 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/versionhistory.rst
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Loading