Skip to content

Fix register_structure_hook for ForwardRef targets - #846

Open
Vinayak19112003 wants to merge 1 commit into
python-attrs:mainfrom
Vinayak19112003:fix-206-forward-ref-register
Open

Vinayak19112003 wants to merge 1 commit into
python-attrs:mainfrom
Vinayak19112003:fix-206-forward-ref-register

Conversation

@Vinayak19112003

Copy link
Copy Markdown

Fixes #206.

BaseConverter.register_structure_hook raised TypeError: Invalid first argument to 'register()'. ForwardRef('...') is not a class or union type. when registering a hook for a typing.ForwardRef (or annotationlib.ForwardRef) target, because it fell through to register_cls_list / functools.singledispatch, which has rejected non-class arguments since the CPython bpo-46032 fix (Python 3.9.10 / 3.10.2).

The fix routes ForwardRef targets through register_func_list with an equality predicate, mirroring the existing handling for type aliases and newtypes — except it uses == instead of is, so a hook registered for ForwardRef("MyClass") also matches an equivalent ForwardRef("MyClass") constructed later.

Why now, when #206's 2022 discussion pointed at register_structure_hook_func instead: the landscape has changed since then. cattrs now has first-class annotationlib.ForwardRef support on main (#741), and on Python 3.14+ (PEP 649/749) ForwardRef annotations show up in attrs-generated constructors without from __future__ import annotations — for example in circular-import scenarios — so users hit this on the documented register_structure_hook API rather than the predicate escape hatch. This is distinct from #201, which is about structuring failing to resolve a forward reference; #206 is about registering a hook for one.

register_unstructure_hook is out of scope for this PR.

Tests: new test_register_structure_hook_for_forward_ref in tests/test_converter.py, parametrized over explicit/decorator registration and BaseConverter/Converter, asserting the registered hook is actually used for structuring: 8 passed after, 8 failed before (with the issue's TypeError). Full test suite on Python 3.12: 986 passed, 15 xfailed. Ruff check and format clean.

Signed-off-by: Vinayak Deshmuk <118991845+Vinayak19112003@users.noreply.github.com>

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.

TypeError when registering ForwardRefs in python 3.10.2

1 participant