You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I would like an easy way to recursively generate attrs classes that have attributes of their type (eg Foo.foo: Foo). Obviously, you can't directly annotate attributes as being of the same type of the class, as the class is not yet generated when specifying attrs attributes. However, Python 3.11 introduces typing.Self, a shortcut to annotating the class. Cattrs could implement this, allowing users to avoid using __attrs_post_init__ to achieve this.
What I Did
# I would like to be able to do this:@defineclassBar:
baz: typing.Self=None@defineclassFoo:
bar: Barstructure({"bar": {"baz": {"baz": None}}}, Foo)
Related discussion about the None default adding making the type annotation implicitly Optional: python/cpython#90353 (comment). This behavior got fixed in Python 3.11+, but it pertains to previous versions.
Activity
Tinche commentedon Aug 7, 2023
Interesting, I wasn't aware attributes could be annotates as
Selfbut according to PEP 673, that's valid!We don't support it yet, so I'll leave this open as an enhancement request.
Your annotation is a little incorrect though, it should be
Self | None.Until we fix the issue, you can use a stringified annotation instead, like this:
This should work.
PIG208 commentedon Aug 8, 2023
Related discussion about the
Nonedefault adding making the type annotation implicitlyOptional: python/cpython#90353 (comment). This behavior got fixed in Python 3.11+, but it pertains to previous versions.ryanwarfield commentedon Aug 8, 2023
Sounds good. I don't use cattrs anymore, but I'm happy that this feature is getting looked at.