Skip to content

Unpacking dictionary with attrs class as attribute #1151

@jhossbach

Description

@jhossbach

Hey there,
I am not sure if this has been answered before, but I noticed something unintuitive when I tried to unstructure a class with another attrs class. This works fine:

@attrs.define
class A:
    a: int
    list_: list[int]
    
dict_ = {"a": 3, "list_": [2,3,4]}
A(**dict_)

# >>> A(a=3, list_=[2, 3, 4])

This on the other hand does not:

import attrs

@attrs.define
class A:
    a: int

@attrs.define
class B:
    a: A
    a_s: list[A]
    
a1, a2 = A(2), A(3)
b = B(a1, [a1, a2])
dict_ = attrs.asdict(b)
 # >>> {'a': {'a': 2}, 'a_s': [{'a': 2}, {'a': 3}]}
B(**dict_)
# >>> B(a={'a': 2}, a_s=[{'a': 2}, {'a': 3}])

Notice how neither a nor a_s is converted back to the proper type. Now I know that cattrs provides a solution to this, namely that I can structure back using cattrs.structure(dict_, B), but I was curious if this is in fact intended behavior or if this is unwanted.
I'd love to hear an explanation why this behavior is desired (if it is)!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions