cattrs
cattrs copied to clipboard
What's the recommended way of handling child classes?
I have something like the following:
from abc import ABC
import attrs
@attrs.define
class Pet(ABC):
name: str
age: int
@attrs.define
class Cat(Pet):
color: str
@attrs.define
class Dog(Pet):
tricks: list[str]
I want to be able to do something like cattrs.structure({"name": "Foo", "age": 2, "color": "pink"}, Pet), and have that instantiate a Cat instead of the generic Pet.
I don't need it to "guess" what class it should be by looking at the attributes. I'm totally fine with including some extra metadata to tell it what class it should be, like type: ClassVar[str] = "cat" or whatever.
I've found the following, which seems to be mostly what I want:
https://cattrs.readthedocs.io/en/latest/unions.html
What I wanted to know is if this is still the recommended approach, or if there's another way.