python-attrs / python-attrs/cattrs

Structure/unstructure decorators for classes

Open
#746 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
1.1k
Forks
159
Avg merge
12h 21m
Merged PRs (30d)
6

Description

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 https://github.com/python-attrs/attrs/issues/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?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by tracing the struct_hook and unstruct_hook interfaces described in the issue, along with how field-specific hooks are currently registered. Determine whether self- or cls-aware decorators can be supported while preserving the default structure/unstructure behavior; done means the proposed class-level interface is feasible and covered by appropriate tests.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.