python-attrs / cattrs

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

Dataclass structuring fails with misleading error message. #521

Open brettc opened 3 months ago

brettc commented 3 months ago

Description

I'm using cattrs to destructure and restructure a complex hierarchy of classes. It is mostly working. But I've boiled down one of the failures to this small example.

What I Did

from __future__ import annotations
from dataclasses import dataclass
from cattrs.preconf.json import make_converter

CONV = make_converter()

@dataclass(kw_only=True)
class A:
    a: str = ""

@dataclass(kw_only=True)
class B:
    b: str = ""

@dataclass(kw_only=True)
class C:
    c: int = 3
    a_or_b: AorB | None = None

AorB = A | B

def test_c_reconstruction():
    c = C(a_or_b=B())
    s = CONV.dumps(c)
    #  attr.exceptions.NotAnAttrsClassError: <class 'tests.test_cattrs_fail.A'> is not an attrs-decorated class.
    c2 = CONV.loads(s, C)