Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion pyrsistent/_checked_types.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import types as _builtin_types
from enum import Enum

from abc import abstractmethod, ABCMeta
from collections.abc import Iterable
from typing import TypeVar, Generic
from typing import TypeVar, Generic, get_origin

from pyrsistent._pmap import PMap, pmap
from pyrsistent._pset import PSet, pset
Expand Down Expand Up @@ -86,6 +87,15 @@ def maybe_parse_user_type(t):
return [t]
elif is_type and not is_iterable:
return [t]
elif isinstance(t, _builtin_types.GenericAlias) or (not is_type and hasattr(t, '__origin__')):
# Parameterized generics like ``tuple[int, int]`` or ``List[str]`` are
# Iterable, but iterating them yields starred self-references that cause
# infinite recursion. Resolve to the bare origin type instead so that
# runtime ``isinstance`` checks work correctly.
origin = get_origin(t)
if origin is not None and isinstance(origin, type):
return [origin]
return [t]
elif is_iterable:
# Recur to validate contained types as well.
ts = t
Expand Down
14 changes: 14 additions & 0 deletions tests/class_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -472,3 +472,17 @@ def __new__(cls, **kwargs):
a = X(y=[])
b = a.set(y=None)
assert a == b


def test_field_type_generic_alias():
"""Parameterized generics (e.g. tuple[int, int]) must not cause infinite recursion."""
class Coords(PClass):
position = field(type=tuple[int, int])
items = field(type=list[str])
mapping = field(type=dict[str, int])

c = Coords(position=(1, 2), items=['a'], mapping={'x': 1})
assert c.position == (1, 2)

with pytest.raises(Exception):
Coords(position='not a tuple', items=[], mapping={})