Skip to content

Commit 0da0ee8

Browse files
committed
fix: resolve recursive sequence declarations on Python 3.10
1 parent 43cdbf3 commit 0da0ee8

7 files changed

Lines changed: 105 additions & 10 deletions

File tree

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# Recursive abstract sequence declarations on Python 3.10
2+
3+
Issue #13 reproduced using standalone CPython 3.10.22, with the actual unchanged decoder on merged main 43cdbf3: 3 failed, 29 passed across existing decoder/validation controls. The three failures were nested Sequence list/tuple reconstruction and unknown child-field rejection. The runtime was unpacked into a private maintenance packet; shared installed Python-introspect 0.2.0 and OpenHCS dependencies were not changed.
4+
5+
The annotation_types owner completes unresolved nested type strings after standard get_type_hints, using the declaring class/module namespace. Decoder and dataclass validator consume that same declaration. Literal values and Annotated metadata remain values; inherited fields use the original declaring module. No version-specific escape, private typing API, annotation cache, or duplicate decoder is added.
6+
7+
Receiving: full existing package suite plus two boundary controls, **145 PASS on CPython 3.10.22 and 145 PASS on CPython 3.12**. The added controls preserve Annotated/Literal metadata, direct nested-type validation, and inherited declarations across modules with conflicting names. Local raw logs: external-ready-cleanup-v1/pi310-red.log, pi310-green.log, pi312-green.log. Existing unrelated Ruff UP007 and SIM102 findings are not claimed repaired.
8+
9+
Version 0.2.1 is a distinct patch declaration; v0.2.0 remains immutable. This PR does not publish wheels or change the shared installed environment.

‎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.0"
7+
version = "0.2.1"
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.0"
12+
__version__ = "0.2.1"
1313

1414
from .signature_analyzer import (
1515
SignatureAnalyzer,

‎src/python_introspect/annotation_types.py‎

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,54 @@
22

33
from __future__ import annotations
44

5+
import sys
56
import types
67
from enum import Enum
7-
from typing import Annotated, Union, get_args, get_origin
8+
from typing import Annotated, Literal, Union, get_args, get_origin, get_type_hints
9+
10+
11+
def resolved_class_annotations(owner: type) -> dict[str, object]:
12+
"""Resolve nested type strings in the class that declared each field.
13+
14+
Python 3.10 leaves strings inside PEP 585 aliases unresolved. Complete
15+
those declarations without interpreting Literal values or Annotated metadata.
16+
"""
17+
annotations = get_type_hints(owner, include_extras=True)
18+
unresolved = set(annotations)
19+
for declaration in owner.__mro__:
20+
class_namespace = dict(vars(declaration))
21+
module = sys.modules.get(declaration.__module__)
22+
module_namespace = {} if module is None else vars(module)
23+
for name in class_namespace.get("__annotations__", {}):
24+
if name in unresolved:
25+
annotations[name] = _resolve_nested_type_strings(
26+
annotations[name], class_namespace, module_namespace
27+
)
28+
unresolved.remove(name)
29+
return annotations
30+
31+
32+
def _resolve_nested_type_strings(annotation: object, globalns: dict, localns: dict) -> object:
33+
if isinstance(annotation, str):
34+
return _resolve_nested_type_strings(eval(annotation, globalns, localns), globalns, localns)
35+
if isinstance(annotation, list):
36+
resolved = [_resolve_nested_type_strings(member, globalns, localns) for member in annotation]
37+
return annotation if all(a is b for a, b in zip(resolved, annotation)) else resolved
38+
origin = get_origin(annotation)
39+
members = get_args(annotation)
40+
if not members or origin is Literal:
41+
return annotation
42+
if origin is Annotated:
43+
base = _resolve_nested_type_strings(members[0], globalns, localns)
44+
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)
46+
if all(member is original for member, original in zip(resolved, members)):
47+
return annotation
48+
if isinstance(annotation, types.GenericAlias):
49+
return types.GenericAlias(origin, resolved)
50+
if is_union_type(annotation):
51+
return Union[resolved] # noqa: UP007 - dynamically derived member tuple
52+
return origin[resolved]
853

954

1055
def is_union_type(annotation: object) -> bool:

‎src/python_introspect/dataclass_projection.py‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,9 @@
1313
TypeVar,
1414
get_args,
1515
get_origin,
16-
get_type_hints,
1716
)
1817

19-
from .annotation_types import is_union_type
18+
from .annotation_types import is_union_type, resolved_class_annotations
2019
from .validation import validate_annotated_dataclass, validate_annotation_value
2120

2221
DataclassT = TypeVar("DataclassT")
@@ -53,7 +52,7 @@ def dataclass_from_mapping(
5352
f"{target_type.__name__} received undeclared field(s): {', '.join(extras)}."
5453
)
5554

56-
annotations = get_type_hints(target_type, include_extras=True)
55+
annotations = resolved_class_annotations(target_type)
5756
decoded_values: dict[str, object] = {}
5857
missing: list[str] = []
5958
for declared_field in declared_fields:

‎src/python_introspect/validation.py‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,11 @@
1414
TypeVar,
1515
get_args,
1616
get_origin,
17-
get_type_hints,
1817
)
1918

2019
from annotated_types import Ge, Gt, Interval, Le, Len, Lt, MaxLen, MinLen, Predicate
2120

22-
from .annotation_types import is_union_type
21+
from .annotation_types import is_union_type, resolved_class_annotations
2322

2423

2524
class AnnotationValidationError(ValueError):
@@ -86,7 +85,7 @@ def validate_annotated_dataclass(instance: object) -> None:
8685
f"got {owner_type.__name__}."
8786
)
8887

89-
annotations = get_type_hints(owner_type, include_extras=True)
88+
annotations = resolved_class_annotations(owner_type)
9089
for declared_field in fields(instance):
9190
annotation = annotations.get(declared_field.name, declared_field.type)
9291
value = object.__getattribute__(instance, declared_field.name)

‎tests/test_dataclass_projection.py‎

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,15 @@
11
from dataclasses import asdict, dataclass, field
22
from enum import Enum
3+
from typing import Annotated, Literal
34
from collections.abc import Sequence
45

56
import pytest
67

7-
from python_introspect import dataclass_from_mapping, project_dataclass
8+
from python_introspect import (
9+
dataclass_from_mapping,
10+
project_dataclass,
11+
validate_annotated_dataclass,
12+
)
813

914

1015
class Mode(Enum):
@@ -254,3 +259,41 @@ class Envelope:
254259

255260
with pytest.raises(TypeError, match="ambiguously matches multiple members"):
256261
dataclass_from_mapping(Envelope, {"payload": {"value": 1}})
262+
263+
264+
@dataclass(frozen=True)
265+
class AnnotatedSequenceEnvelope:
266+
nodes: Annotated[Sequence["RecursiveSequenceNode"], "display text"]
267+
state: Literal["unresolved_name"] = "unresolved_name"
268+
269+
270+
def test_nested_resolution_preserves_annotation_metadata_and_literal_values():
271+
result = dataclass_from_mapping(
272+
AnnotatedSequenceEnvelope, {"nodes": [{"name": "child"}]}
273+
)
274+
assert result == AnnotatedSequenceEnvelope((RecursiveSequenceNode("child"),))
275+
with pytest.raises(TypeError, match=r"children\[0\]"):
276+
validate_annotated_dataclass(RecursiveSequenceNode("parent", ({"name": "child"},)))
277+
278+
279+
def test_inherited_nested_types_use_the_declaring_module_namespace(monkeypatch):
280+
import sys
281+
from types import ModuleType
282+
283+
base_module = ModuleType("sequence_base_declaration")
284+
child_module = ModuleType("sequence_child_declaration")
285+
monkeypatch.setitem(sys.modules, base_module.__name__, base_module)
286+
monkeypatch.setitem(sys.modules, child_module.__name__, child_module)
287+
exec(
288+
'from dataclasses import dataclass\nfrom collections.abc import Sequence\n'
289+
'@dataclass\nclass Leaf:\n name: str\n'
290+
'@dataclass\nclass Base:\n children: Sequence["Leaf"]\n',
291+
vars(base_module),
292+
)
293+
exec(
294+
'from sequence_base_declaration import Base\n'
295+
'Leaf = int\nclass Child(Base):\n pass\n',
296+
vars(child_module),
297+
)
298+
result = dataclass_from_mapping(child_module.Child, {"children": [{"name": "child"}]})
299+
assert isinstance(result.children[0], base_module.Leaf)

0 commit comments

Comments
 (0)