python-attrs / python-attrs/cattrs
Converter ignores fields from child class when unstructuring (inheritance)
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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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