Skip to content

Commit

Permalink
Don't fail when parsing types with invalid __parameters__
Browse files Browse the repository at this point in the history
  • Loading branch information
jcrist committed Nov 15, 2024
1 parent 148f9a1 commit 595c33c
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
20 changes: 15 additions & 5 deletions msgspec/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,22 @@ def _eval_type(t, globalns, localns):


def _apply_params(obj, mapping):
if params := getattr(obj, "__parameters__", None):
args = tuple(mapping.get(p, p) for p in params)
return obj[args]
elif isinstance(obj, typing.TypeVar):
if isinstance(obj, typing.TypeVar):
return mapping.get(obj, obj)
return obj

try:
parameters = tuple(obj.__parameters__)
except Exception:
# Not parameterized or __parameters__ is invalid, ignore
return obj

if not parameters:
# Not parametrized
return obj

# Parametrized
args = tuple(mapping.get(p, p) for p in parameters)
return obj[args]


def _get_class_mro_and_typevar_mappings(obj):
Expand Down
11 changes: 11 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,3 +190,14 @@ class Sub2(Sub, Base[int]):
z: str

assert get_class_annotations(Sub2) == {"x": int, "y": float, "z": str}

def test_generic_invalid_parameters(self):
class Invalid:
@property
def __parameters__(self):
pass

class Sub(Base[Invalid]):
pass

assert get_class_annotations(Sub) == {"x": Invalid}

0 comments on commit 595c33c

Please sign in to comment.