python-attrs / python-attrs/cattrs

Inheriting overrides

Open
#538 3 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

  • cattrs version: 23.2.3
  • Python version: 3.9
  • Operating System: macOS
Description

I am wondering if cattrs provides a clever built-in mechanism reuse/inherit overrides from another class. It sounds like an easy problem at first, but I really can't figure out a smart way to achieve it.

What I Did

Consider the following code example and let's assume I have an entire class hierarchy below FruitBasket. In this example, I want that apples are always unstructured as bananas no matter where we are in the class hierarchy. In addition, the subclasses themselves might want to add their own custom overrides:

import cattrs
from attrs import define
from cattrs.gen import make_dict_unstructure_fn


@define
class FruitBasket:
    apples: int


@define
class MixedBasket(FruitBasket):
    oranges: int


converter = cattrs.Converter()
converter.register_unstructure_hook(
    FruitBasket,
    make_dict_unstructure_fn(
        FruitBasket, converter, apples=cattrs.override(rename="bananas")
    ),
)
converter.register_unstructure_hook(
    MixedBasket,
    make_dict_unstructure_fn(
        MixedBasket, converter, oranges=cattrs.override(rename="peaches")
    ),
)

print(converter.unstructure(MixedBasket(apples=5, oranges=3)))

So the goal is that the latter gives a {'bananas': 5, 'peaches': 3}, which I can of course achieve by adding the override again to the second hook. However, my question is if there is an automatic way to do so, which doesn't require me to keep track of the overrides while going to down the hierarchy and register them again and again.

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 cattrs.Converter hook registration and make_dict_unstructure_fn, using the FruitBasket and MixedBasket example to trace how class-specific overrides are applied. Define whether inherited overrides should be discovered automatically while preserving subclass overrides, then verify the intended result is {'bananas': 5, 'peaches': 3}.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.