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

fix: avoid RecursionError when using some types like Enum or Literal with generic models #2438

Merged
merged 4 commits into from Mar 3, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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/2436-PrettyWood.md
@@ -0,0 +1 @@
Support properly `Enum` when combined with generic models
3 changes: 2 additions & 1 deletion pydantic/generics.py
@@ -1,5 +1,6 @@
import sys
import typing
from enum import Enum
from typing import (
TYPE_CHECKING,
Any,
Expand Down Expand Up @@ -211,7 +212,7 @@ def iter_contained_typevars(v: Any) -> Iterator[TypeVarType]:
yield v
elif hasattr(v, '__parameters__') and not get_origin(v) and lenient_issubclass(v, GenericModel):
yield from v.__parameters__
elif isinstance(v, Iterable):
elif isinstance(v, Iterable) and not lenient_issubclass(v, Enum):
PrettyWood marked this conversation as resolved.
Show resolved Hide resolved
for var in v:
yield from iter_contained_typevars(var)
else:
Expand Down
18 changes: 18 additions & 0 deletions tests/test_generics.py
Expand Up @@ -1039,3 +1039,21 @@ class Model2(GenericModel, Generic[T]):
Model2 = module.Model2
result = Model1[str].parse_obj(dict(ref=dict(ref=dict(ref=dict(ref=123)))))
assert result == Model1(ref=Model2(ref=Model1(ref=Model2(ref='123'))))


@skip_36
def test_generic_enum():
T = TypeVar('T')

class SomeGenericModel(GenericModel, Generic[T]):
some_field: T

class SomeStringEnum(str, Enum):
A = 'A'
B = 'B'

class MyModel(BaseModel):
my_gen: SomeGenericModel[SomeStringEnum]

m = MyModel.parse_obj({'my_gen': {'some_field': 'A'}})
assert m.my_gen.some_field is SomeStringEnum.A