Skip to content

Inheriting overrides #538

Open
Open
@AdrianSosic

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.

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions