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

Bug fix for forward refs in generics #6157

Merged
merged 5 commits into from
Jun 23, 2023
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/6130-mark-todd.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed bug with generics receiving forward refs
14 changes: 12 additions & 2 deletions pydantic/generics.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
Any,
ClassVar,
Dict,
ForwardRef,
Generic,
Iterator,
List,
Expand All @@ -19,7 +20,7 @@
)
from weakref import WeakKeyDictionary, WeakValueDictionary

from typing_extensions import Annotated
from typing_extensions import Annotated, Literal as ExtLiteral

from .class_validators import gather_all_validators
from .fields import DeferredType
Expand All @@ -30,6 +31,8 @@

if sys.version_info >= (3, 10):
from typing import _UnionGenericAlias
if sys.version_info >= (3, 8):
from typing import Literal

GenericModelT = TypeVar('GenericModelT', bound='GenericModel')
TypeVarType = Any # since mypy doesn't allow the use of TypeVar as a type
Expand Down Expand Up @@ -267,6 +270,8 @@ def replace_types(type_: Any, type_map: Mapping[Any, Any]) -> Any:
annotated_type, *annotations = type_args
return Annotated[replace_types(annotated_type, type_map), tuple(annotations)]

if (origin_type is ExtLiteral) or (sys.version_info >= (3, 8) and origin_type is Literal):
return type_map.get(type_, type_)
# Having type args is a good indicator that this is a typing module
# class instantiation or a generic alias of some sort.
if type_args:
Expand Down Expand Up @@ -317,7 +322,12 @@ def replace_types(type_: Any, type_map: Mapping[Any, Any]) -> Any:

# If all else fails, we try to resolve the type directly and otherwise just
# return the input with no modifications.
return type_map.get(type_, type_)
new_type = type_map.get(type_, type_)
# Convert string to ForwardRef
if isinstance(new_type, str):
return ForwardRef(new_type)
else:
return new_type


def check_parameters_count(cls: Type[GenericModel], parameters: Tuple[Any, ...]) -> None:
Expand Down