Skip to content

Structure/unstructure decorators for classes #746

Open

Description

@LecrisUT

I am not sure if I am missing some interface that can already do this, but I want to ultimately get something along these lines:

@attrs.define
class Example:
    normal_field: str
    special_field: str
    prefix: ClassVar[str] = "something"

    @special_field.structure
    def _special_field_structure(self, attrib) -> str:
        return f"{self.prefix}:{self.special_field}"

    @special_field.unstructure
    @classmethod
    def _special_field_unstructure(cls, attrib, value: str) -> str:
        prefix, value = value.split(":")
        assert prefix == cls.prefix
        return value

The whole prefix and handling is unimportant, it's just the interface here that I want to highlight.

Basically I want to use some default structure/unstructure functions (just changing _ to -), but allow some special fields to have a more complicated handling if needed by decorating some functions to handle things in a different way. The part where I extend the field decorators provided by attrs is related to python-attrs/attrs#1543, let's just assume that that just works. The obstacle here is that the struct_hook/unstruct_hook do not accept self/cls interface as the first argument is always the raw value to be translated.

Any ideas if this could be enabled?

Activity

  1. Tinche commented on Apr 14, 2026

    @Tinche
    Member

    An interesting idea. Note that it's somewhat against the spirit of cattrs to stick serialization logic on the models, but we've been relaxing this over the years (see the use_class_methods strategy and the Annotated support in the last release).

    I wonder if an attrs field transformer could be used to change the type of special_field from str to Annotated[str, override(struct_hook=..., unstruct_hook=...)]. This is also where you could adapt Example._special_field_unstructure(attrib, value) into the cattrs unstructure signature.

  2. LecrisUT commented on Apr 14, 2026

    @LecrisUT
    Author

    the Annotated support in the last release

    Oh neat, did not know that is already in since attrs does not seem to have a support for it yet. That is indeed an interesting way to avoid some de-duplication. But a question for both attrs and cattrs on that subject, what would third-party extensions look like in that context. I could see the third-party extensions extending upon something like

    class AttrsMetadata:
        _Metadata_name: ClassVar[str]
        """The dict key to populate in the field metadata""""
    
    @attrs.define
    class MyMetadata(AttrsMetadata):
        _Metadata_name = "my_ext"
        factor: int
    
    @attrs.define
    class Example:
        var: Annotated[int, MyMetadata(5)] = field()
    
        @var.converter
        def _var_convert(self, attribute, value):
            return value * attribute.metadata["my_ext"].factor
    

    see the use_class_methods strategy

    I see, that is a bit different. That creates a structure/unstructure for the whole class, but what I am looking for is more specific to the specific fields.

    I wonder if an attrs field transformer could be used to change the type of special_field from str to Annotated[str, override(struct_hook=..., unstruct_hook=...)].

    Hmm also neat, will play around with it. What interface I was looking initially is the @<field>.custom_decorator, which kinda works pending a patch and a usage of an inner class. If the thing is converted to Annotated, then using generic TypeAlias would be better.

    The one neat thing of the decorator approach is the ability to chain the functions. That could also work for the struct/unstruct to build up from a default handler.

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