Open philpep opened 1 year ago
ForwardRef
or a NewType
hook.We need to improve make_dict_structure_fn
to take into account classes we're already in the process of generating (or just catch the RecursionError, but that's less efficient). #299 is just because we don't support typing.Self
I think.
Hi,
Does a workaround / solution exist for this yet?
I think a workaround would be using ForwardRef or a NewType hook.
Is there an example of how to do this anywhere?
I ended up coming up with this workaround:
@attrs.define
class Foo:
nested_dict: dict[str, Foo] = attrs.field(factory=dict)
converter = cattrs.Converter()
# Overriding the deserialization of this type is necessary to prevent an infinite recursion bug:
# https://github.com/python-attrs/cattrs/issues/409
def structure_nested_dict(
nested_dict: dict[str, Any], _: type[dict[str, Foo]]
) -> dict[str, Foo]:
return {key: converter.structure(val, Foo) for key, val in nested_dict.items()}
converter.register_structure_hook(
Foo,
cattrs.gen.make_dict_structure_fn(
Foo,
converter,
nested_dict=cattrs.gen.override(struct_hook=structure_nested_dict),
),
)
Description
Hi, I've RecursionError raised when structuring nested class.
What I Did
Here's a minimal code triggering the issue:
And part of the traceback: