From 9093a3a5be2d7e6dbef6143d93e400b0a57a67a4 Mon Sep 17 00:00:00 2001 From: Davis Kirkendall Date: Wed, 24 Feb 2021 10:24:49 +0100 Subject: [PATCH] Add test for generic aliases and lenient_issubclass --- pydantic/utils.py | 9 +++++++-- tests/test_utils.py | 8 ++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/pydantic/utils.py b/pydantic/utils.py index ab2f3bcdfcb..7ae72b2a27c 100644 --- a/pydantic/utils.py +++ b/pydantic/utils.py @@ -24,7 +24,7 @@ no_type_check, ) -from .typing import NoneType, display_as_type +from .typing import NoneType, display_as_type, GenericAlias from .version import version_info if TYPE_CHECKING: @@ -149,7 +149,12 @@ def validate_field_name(bases: List[Type['BaseModel']], field_name: str) -> None def lenient_issubclass(cls: Any, class_or_tuple: Union[Type[Any], Tuple[Type[Any], ...]]) -> bool: - return isinstance(cls, type) and issubclass(cls, class_or_tuple) + try: + return isinstance(cls, type) and issubclass(cls, class_or_tuple) + except TypeError: + if isinstance(cls, GenericAlias): + return False + raise def in_ipython() -> bool: diff --git a/tests/test_utils.py b/tests/test_utils.py index dd45ca1483b..52e4b81af86 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -109,6 +109,14 @@ class A(str): assert lenient_issubclass(A, str) is True +@pytest.mark.skipif(sys.version_info < (3, 9), reason='generic aliases are not available in python < 3.9') +def test_lenient_issubclass_with_generic_aliases(): + from collections.abc import Mapping + + # should not raise an error here: + assert lenient_issubclass(list[str], Mapping) is False + + def test_lenient_issubclass_is_lenient(): assert lenient_issubclass('a', 'a') is False