python-attrs / python-attrs/cattrs

Feature request: "flatten" operation for cattrs.gen

Open
#352 0 comments 3 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

For a thing at work, I implemented some [un]structure hook factories that wrap make_dict_structure_fn and make_dict_unstructure_fn to support flattening an attribute, like this:

@define
class A:
    a: int
    b: int

@define
class C:
    a: A
    c: int

converter = ...  # set up a converter with my wrappers

assert converter.unstructure(C(A(1, 2), 3)) == {'a': 1, 'b': 2, 'c': 3}

I'd like to upstream this support. The basic idea is to implement functionality similar to Serde's Struct flattening by extending the override function to take a flatten: bool argument that defaults to False and then adjusting make_dict_structure_fn and make_dict_unstructure_fn to use it.

I'm willing to work on this, but wanted to get feedback from folks here before I start.

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 reading the existing override function and the make_dict_structure_fn and make_dict_unstructure_fn entry points. Trace how field overrides are applied in both directions, then define the flatten behavior around the provided A and C example. Done means the proposed flatten option works for structure and unstructure while preserving existing behavior by default.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.