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 TypeError for GenericModel with Callable param #4653

Merged
merged 2 commits into from Oct 31, 2022
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/4551-mfulgo.md
@@ -0,0 +1 @@
Fix GenericModel with Callable param raising a TypeError
samuelcolvin marked this conversation as resolved.
Show resolved Hide resolved
6 changes: 5 additions & 1 deletion pydantic/generics.py
Expand Up @@ -64,7 +64,11 @@ def __class_getitem__(cls: Type[GenericModelT], params: Union[Type[Any], Tuple[T
"""

def _cache_key(_params: Any) -> Tuple[Type[GenericModelT], Any, Tuple[Any, ...]]:
return cls, _params, get_args(_params)
args = get_args(_params)
# python returns a list for Callables, which is not hashable
if len(args) == 2 and isinstance(args[0], list):
args = (tuple(args[0]), args[1])
return cls, _params, args

cached = _generic_types_cache.get(_cache_key(params))
if cached is not None:
Expand Down
27 changes: 27 additions & 0 deletions tests/test_generics.py
Expand Up @@ -7,6 +7,7 @@
ClassVar,
Dict,
Generic,
Iterable,
List,
Mapping,
Optional,
Expand Down Expand Up @@ -234,6 +235,32 @@ class Model(GenericModel, Generic[T]):
assert len(_generic_types_cache) == cache_size + 2


def test_cache_keys_are_hashable():
cache_size = len(_generic_types_cache)
T = TypeVar('T')
C = Callable[[str, Dict[str, Any]], Iterable[str]]

class MyGenericModel(GenericModel, Generic[T]):
t: T

# Callable's first params get converted to a list, which is not hashable.
# Make sure we can handle that special case
Simple = MyGenericModel[Callable[[int], str]]
assert len(_generic_types_cache) == cache_size + 2
# Nested Callables
MyGenericModel[Callable[[C], Iterable[str]]]
assert len(_generic_types_cache) == cache_size + 4
MyGenericModel[Callable[[Simple], Iterable[int]]]
assert len(_generic_types_cache) == cache_size + 6
MyGenericModel[Callable[[MyGenericModel[C]], Iterable[int]]]
assert len(_generic_types_cache) == cache_size + 10

class Model(BaseModel):
x: MyGenericModel[Callable[[C], Iterable[str]]] = Field(...)

assert len(_generic_types_cache) == cache_size + 10


def test_generic_config():
data_type = TypeVar('data_type')

Expand Down