Skip to content

Structure/unstructure decorators for classes #746

@LecrisUT

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?

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