python-attrs / cattrs

Composable custom class converters for attrs, dataclasses and friends.
https://catt.rs
MIT License
818 stars 113 forks source link

Structure doesn't work with sub-classes #360

Closed ares-b closed 1 year ago

ares-b commented 1 year ago

Description

Cattrs cannot structure My Class if one of my attributes type is a Parent Type of other Child types.

What I Did

import attrs
import cattrs

@attrs.define
class A:
    pass

@attrs.define
class B(A):
    z: float = attrs.field(validator=attrs.validators.instance_of(float))

@attrs.define
class MyClass:
    test: A = attrs.field(validator=attrs.validators.instance_of(A))

mbis = cattrs.structure({"test":  {"z": 3.0}}, MyClass)
# mbis = MyClass(test=A())
# should be MyClass(test=B(z=3.0))
Tinche commented 1 year ago

You might want to keep an eye on https://github.com/python-attrs/cattrs/pull/312, I think that's what you're after.