python-attrs / python-attrs/cattrs

What's the recommended way of handling child classes?

Open
#246 0 comments 0 reactions 0 assignees View on GitHub

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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.