python-attrs / python-attrs/cattrs

Converter ignores fields from child class when unstructuring (inheritance)

Open
#272 11 comments 4 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

  • cattrs version: current master (a10ad1c638dd16308c9aa73c649fa92282503c00)
  • Python version: 3.10
  • Operating System: Linux
Description

I'm serializing a dataclass with a field. If the field has a more generic type than the actual instance, all the information from the child class is lost when unstructuring.

What I Did
from dataclasses import dataclass

import cattr


@dataclass(kw_only=True, frozen=True)
class Bar:
    x: int


@dataclass(kw_only=True, frozen=True)
class Foo(Bar):
    y: int


@dataclass(kw_only=True, frozen=True)
class Baz:
    foo: Bar

converter = cattr.Converter()
foo = Baz(foo=Foo(x=1, y=2))
print("unstructured", converter.unstructure(foo))

Expectation vs Reality

I'd expect it to output unstructured {'foo': {'x': 1, 'y': 2}} but it outputs unstructured {'foo': {'x': 1}}

Is this expected behaviour due to the way Converter generates unstructuring functions? If so, how can you change that behaviour?

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 with the cattr.Converter().unstructure call and the dataclass inheritance example in the issue. Reproduce the output difference between Bar and Foo, then trace how unstructuring handles the declared Bar field versus the runtime Foo instance. Done means the example includes both x and y without breaking existing unstructuring behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.