Skip to content

Commit b56ea76

Browse files
authored
Merge pull request #18 from OpenHCSDev/fix/recursive-type-alias-py310
Stop recursive type alias expansion on Python 3.10 (0.2.4)
2 parents c008baa + c592688 commit b56ea76

5 files changed

Lines changed: 73 additions & 9 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@
22

33
0.2.2 is the first 0.2.x release published to PyPI. The 0.2.0 and 0.2.1 tags exist in git, but their publish runs were cancelled, so upgrading from PyPI goes straight from 0.1.16 to 0.2.2. The notes below cover every change in that jump.
44

5+
## 0.2.4
6+
7+
Fixed:
8+
- `dataclass_from_mapping` and `validate_annotated_dataclass` no longer raise `RecursionError` on Python 3.10 for fields declared with a recursive type alias such as `V = str | list["V"] | dict[str, "V"]`. Since 0.2.1, nested type strings were expanded on 3.10 with no stop, so a self-reference expanded forever. Expansion now stops at a self-reference and leaves it as a `ForwardRef`, which is what `get_type_hints` returns on Python 3.11 and later, so the decoder sees the same declaration on every version.
9+
510
## 0.2.3
611

712
Added:

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
44

55
[project]
66
name = "python-introspect"
7-
version = "0.2.3"
7+
version = "0.2.4"
88
description = "Pure Python introspection toolkit for function signatures, dataclasses, and type hints"
99
readme = "README.md"
1010
requires-python = ">=3.10"

‎src/python_introspect/__init__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
type resolution for framework-specific types (lazy configs, proxies, etc.)
1010
"""
1111

12-
__version__ = "0.2.3"
12+
__version__ = "0.2.4"
1313

1414
from .signature_analyzer import (
1515
SignatureAnalyzer,

‎src/python_introspect/annotation_types.py‎

Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,25 @@
55
import sys
66
import types
77
from enum import Enum
8-
from typing import Annotated, Literal, Union, get_args, get_origin, get_type_hints
8+
from typing import (
9+
Annotated,
10+
ForwardRef,
11+
Literal,
12+
Union,
13+
get_args,
14+
get_origin,
15+
get_type_hints,
16+
)
917

1018

1119
def resolved_class_annotations(owner: type) -> dict[str, object]:
1220
"""Resolve nested type strings in the class that declared each field.
1321
1422
Python 3.10 leaves strings inside PEP 585 aliases unresolved. Complete
1523
those declarations without interpreting Literal values or Annotated metadata.
24+
A recursive alias such as ``V = int | list["V"]`` names itself; the inner
25+
reference is left as a ``ForwardRef``, the form ``get_type_hints`` produces
26+
for it on Python 3.11 and later.
1627
"""
1728
annotations = get_type_hints(owner, include_extras=True)
1829
unresolved = set(annotations)
@@ -29,20 +40,34 @@ def resolved_class_annotations(owner: type) -> dict[str, object]:
2940
return annotations
3041

3142

32-
def _resolve_nested_type_strings(annotation: object, globalns: dict, localns: dict) -> object:
43+
def _resolve_nested_type_strings(
44+
annotation: object,
45+
globalns: dict,
46+
localns: dict,
47+
expanding: frozenset[str] = frozenset(),
48+
) -> object:
3349
if isinstance(annotation, str):
34-
return _resolve_nested_type_strings(eval(annotation, globalns, localns), globalns, localns)
50+
if annotation in expanding:
51+
return ForwardRef(annotation)
52+
return _resolve_nested_type_strings(
53+
eval(annotation, globalns, localns), globalns, localns, expanding | {annotation}
54+
)
3555
if isinstance(annotation, list):
36-
resolved = [_resolve_nested_type_strings(member, globalns, localns) for member in annotation]
56+
resolved = [
57+
_resolve_nested_type_strings(member, globalns, localns, expanding)
58+
for member in annotation
59+
]
3760
return annotation if all(a is b for a, b in zip(resolved, annotation)) else resolved
3861
origin = get_origin(annotation)
3962
members = get_args(annotation)
4063
if not members or origin is Literal:
4164
return annotation
4265
if origin is Annotated:
43-
base = _resolve_nested_type_strings(members[0], globalns, localns)
66+
base = _resolve_nested_type_strings(members[0], globalns, localns, expanding)
4467
return annotation if base is members[0] else Annotated[(base, *members[1:])]
45-
resolved = tuple(_resolve_nested_type_strings(member, globalns, localns) for member in members)
68+
resolved = tuple(
69+
_resolve_nested_type_strings(member, globalns, localns, expanding) for member in members
70+
)
4671
if all(member is original for member, original in zip(resolved, members)):
4772
return annotation
4873
if isinstance(annotation, types.GenericAlias):

‎tests/test_dataclass_projection.py‎

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from dataclasses import asdict, dataclass, field
22
from enum import Enum
33
from typing import Annotated, Literal
4-
from collections.abc import Sequence
4+
from collections.abc import Mapping, Sequence
55

66
import pytest
77

@@ -297,3 +297,37 @@ def test_inherited_nested_types_use_the_declaring_module_namespace(monkeypatch):
297297
)
298298
result = dataclass_from_mapping(child_module.Child, {"children": [{"name": "child"}]})
299299
assert isinstance(result.children[0], base_module.Leaf)
300+
301+
302+
WireValue = (
303+
str
304+
| int
305+
| float
306+
| bool
307+
| None
308+
| list["WireValue"]
309+
| tuple["WireValue", ...]
310+
| dict[str, "WireValue"]
311+
)
312+
313+
314+
@dataclass(frozen=True)
315+
class WireEnvelope:
316+
sequence: int
317+
event: Mapping[str, WireValue] | None
318+
319+
320+
def test_recursive_type_alias_decodes_nested_values() -> None:
321+
# Python 3.10 keeps "WireValue" as a string inside the PEP 585 aliases;
322+
# resolving it must stop where the alias names itself.
323+
payload = {
324+
"sequence": 1,
325+
"event": {
326+
"phase": "compile",
327+
"percent": 50.0,
328+
"context": {"axes": ["A01"], "details": [{"ready": True, "error": None}]},
329+
},
330+
}
331+
result = dataclass_from_mapping(WireEnvelope, payload)
332+
assert result == WireEnvelope(1, payload["event"])
333+
validate_annotated_dataclass(result)

0 commit comments

Comments
 (0)