Skip to content

Resolve forward references nested in other annotations - #827

Open
Aschenbath wants to merge 1 commit into
python-attrs:mainfrom
Aschenbath:fix-201-forwardref-resolution
Open

Aschenbath wants to merge 1 commit into
python-attrs:mainfrom
Aschenbath:fix-201-forwardref-resolution

Conversation

@Aschenbath

Copy link
Copy Markdown

Fixes #201.

Without PEP 563, a quoted forward reference nested in another annotation — like y: Optional["Y"] in a mutually recursive pair of attrs classes — survived into dispatch and failed with StructureHandlerNotFoundError: Unsupported type: ForwardRef('Y'), while the same code worked with from __future__ import annotations.

adapted_fields only triggered type resolution when a field's type was a plain string (the PEP 563 shape). It now uses a small _contains_forward_ref helper that also detects ForwardRefs nested inside typing constructs (via get_args), for both attrs classes and dataclasses, and resolves the class's types in that case (attrs.resolve_types / get_type_hints respectively).

Tests:

  • Added test_structure_quoted_forward_refs to tests/test_structure.py with the issue's mutually recursive example.
  • Regression runs: tests/test_structure.py, tests/test_recursive.py, tests/test_gen_dict.py, tests/test_dicts.py (141 passed); tests/test_gen_dict_563.py, tests/test_tuples_563.py, tests/test_generics.py, tests/test_generics_649.py, tests/test_generics_nested.py, tests/test_baseconverter.py, tests/test_typeddicts.py, tests/test_preconf.py (183 passed, 20 skipped; 2 pre-existing test_tomllib_converter* failures also occur on unmodified upstream main in this environment).
  • ruff check and ruff format on the changed files: pass.

A changelog entry is included in HISTORY.md.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ForwardRef and GenConverter do not seem to work together

1 participant