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

Add test for generic aliases and lenient_issubclass #2392

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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions changes/2399-daviskirk.md
@@ -0,0 +1 @@
fix: allow `utils.lenient_issubclass` to handle `typing.GenericAlias` objects like `list[str]` in python >= 3.9.
1 change: 1 addition & 0 deletions pydantic/typing.py
Expand Up @@ -221,6 +221,7 @@ def get_args(tp: Type[Any]) -> Tuple[Any, ...]:
'CallableGenerator',
'ReprArgs',
'CallableGenerator',
'GenericAlias',
'get_args',
'get_origin',
'typing_base',
Expand Down
9 changes: 7 additions & 2 deletions pydantic/utils.py
Expand Up @@ -24,7 +24,7 @@
no_type_check,
)

from .typing import NoneType, display_as_type
from .typing import GenericAlias, NoneType, display_as_type
from .version import version_info

if TYPE_CHECKING:
Expand Down Expand Up @@ -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 # pragma: no cover


def in_ipython() -> bool:
Expand Down
8 changes: 8 additions & 0 deletions tests/test_utils.py
Expand Up @@ -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

Expand Down