python-attrs / python-attrs/cattrs
What's the recommended way of handling child classes?
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 1.1k
- Forks
- 159
- Avg merge
- 12h 21m
- Merged PRs (30d)
- 6
Description
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.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the polymorphic structuring guidance in the linked unions documentation and compare it with the cattrs.structure call shown in the issue. A useful outcome would be a decided recommended approach, with any required metadata or configuration and a documented example for structuring Pet subclasses.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- backend
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100