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

Don't fail when parsing types with invalid __parameters__ #772

Merged
merged 1 commit into from
Nov 15, 2024
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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}
Loading