python-attrs / cattrs

Composable custom class converters for attrs, dataclasses and friends.
https://catt.rs
MIT License
829 stars 113 forks source link

Is there a way to recursively prefer `_cattrs_use_alias=True`? #596

Closed BrianPugh closed 3 weeks ago

BrianPugh commented 3 weeks ago

In my application, i have several nested structures that have attrs aliases set (e.g. field(..., alias="foo")). I am aware that I could individually register a hook for every class with:

converter.register_structure_hook(
    MyClass,
    make_dict_structure_fn(MyClass, converter, _cattrs_use_alias=True),
)

However, this requires the developer to remember to do that for every new class. Is there a way of applying this setting for the whole converter?

BrianPugh commented 3 weeks ago

I think the solution is:

import attrs
import cattrs

converter.register_structure_hook_factory(
    attrs.has,
    lambda cl: cattrs.gen.make_dict_structure_fn(cl, converter, _cattrs_use_alias=True)
)

would love to have @Tinche to chime in if this is the intended solution (and then close this issue)! Thanks!

Tinche commented 3 weeks ago

You got to it before I did! That's exactly what I would have suggested.

BrianPugh commented 3 weeks ago

thank you!