python-attrs / python-attrs/cattrs

ForwardRef and GenConverter do not seem to work together

Open
#201 15 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
1.1k
Forks
159
Avg merge
12h 21m
Merged PRs (30d)
6

Description

  • cattrs version: 1.8.0 (attrs 21.2.0)
  • Python version: 3.9.7
  • Operating System: Windows 10
Description

When using recursive types (see example below), structure with GenConverter raises a StructureHandlerNotFoundError with the message "Unsupported type: ForwardRef('Y'). Register a structure hook for it"
.
The error does not happen with PEP 563 enabled. That means when we add 'from future import annotations' to the program and
replace y: typing.Optional['Y'] with y: typing.Optional[Y] everything works as expected.

What I Did
import typing
import cattr
import attr

@attr.define(auto_attribs=True)
class X:
    a: int
    b: float
    y: typing.Optional['Y']   #with PEP563 enabled:   y: typing.Optional[Y]   (that does not raise an exception) 

@attr.define(auto_attribs=True)
class Y:
    a: typing.List[int]
    x: X


converter = cattr.GenConverter()

data = { 'a': [1,2,3], 'x': {'a':1, 'b':2.000001, 'y': {'a': [], 'x': {'a': 5, 'b': 3.1, 'y': None}}} }
d = converter.structure( data, Y )  # <---- raises StructureHandlerNotFoundError    Unsupported type: ForwardRef('Y'). Register a structure hook for it

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the supplied Python reproducer with cattrs 1.8.0 and trace the GenConverter structure path for the recursive ForwardRef('Y'). Compare this behavior with the PEP 563 variant; done means the original example structures successfully without requiring a manually registered hook.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.