Skip to content

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

Closed

Description

@BrianPugh

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?

Activity

  1. BrianPugh commented on Nov 5, 2024

    @BrianPugh
    Author

    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!

  2. Tinche commented on Nov 5, 2024

    @Tinche
    Member

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

  3. BrianPugh commented on Nov 5, 2024

    @BrianPugh
    Author

    thank you!

  4. AdrianSosic commented on Jun 23, 2025

    @AdrianSosic
    Contributor

    Hi @Tinche, I just stumbled over this issue because I was looking for the same functionality. While the proposed solution works, is comes with the downside that you need to remember setting the flag whenever you register a regular singledispatch hook for a class using make_dict_structure_fn, because that takes preference over the hook factory. And if you forget, this might break your exposed APIs that rely on these converters.

    Therefore a question: wouldn't it perhaps make sense to add a use_alias argument to Converter that is then extracted a la from_converter in make_dict_(un)structure_fn_from_attrs, just like other settings such as forbid_extra_keys? The nice consequence would be that this would then work together with added hooks, if I'm not mistaken?

  5. Tinche commented on Jun 23, 2025

    @Tinche
    Member

    Hm, if you want to contribute it, sure, why not.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

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