Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nested class structure #542

Closed
csqzhang opened this issue Jun 1, 2024 · 4 comments · Fixed by #540
Closed

Nested class structure #542

csqzhang opened this issue Jun 1, 2024 · 4 comments · Fixed by #540
Labels
Milestone

Comments

@csqzhang
Copy link

csqzhang commented Jun 1, 2024

  • cattrs version: cattrs==23.2.3
  • Python version: python=3.11.2
  • Operating System: OSX/Linux

Description

I want to use cattrs to (un)strcuture classes.

What I Did

import cattr
import attr
from cattrs.strategies import configure_tagged_union, include_subclasses

@attr.s(frozen=True, auto_attribs=True)
class A:
    pass


@attr.s(frozen=True, auto_attribs=True)
class B1(A):
    b: str


@attr.s(frozen=True, auto_attribs=True)
class B2(A):
    b: str
    a: A


CONVERTER = cattr.Converter()
union_strategy = partial(configure_tagged_union, tag_name="type_name")
include_subclasses(A, CONVERTER, union_strategy=union_strategy)


if __name__ == "__main__":
    instance = B1(b="1")
    r = CONVERTER.unstructure(instance)
    CONVERTER.structure(r, A)
    instance2 = B2(b="2", a=B1(b="1"))
    r2 = CONVERTER.unstructure(instance2)
    CONVERTER.structure(r2, A)

In the example above, we can (un)structure a B1 instance (e.g. instance) correctly. However, for a B2 instance (e.g. instance2), I can see catter unstructure it correctly, r2 looks correctly. However, I got B2(b='2', a=A()) back when I structure the r2 as A, which does not equal to the original instance2.

@Tinche
Copy link
Member

Tinche commented Jun 1, 2024

Can confirm the issue. Working on a fix now ;)

@Tinche Tinche linked a pull request Jun 1, 2024 that will close this issue
@Tinche Tinche added this to the 24.1 milestone Jun 1, 2024
@Tinche Tinche added the bug label Jun 1, 2024
@Tinche
Copy link
Member

Tinche commented Jun 1, 2024

I've also added a test for this modeled on your case.

@csqzhang
Copy link
Author

csqzhang commented Jun 1, 2024

@Tinche thanks for the work. just wondering when the release will happen?

@Tinche
Copy link
Member

Tinche commented Jun 1, 2024

I'm finishing it up, a couple of weeks probably.

Feel free to use git main if you're in a rush, I try to keep it very stable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants