Custom unstructure function is not called when a union type is wrapped in generic types multiple times
Nobody has claimed this yet.
Assessment
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Newbie friendliness
- 45/100
Research direction
Start by running the provided Python reproduction with cattrs 22.2.0 and Python 3.9, then trace how the converter handles the custom hooks for Optional[list[Union[A, B]]]. Done means the assertions for _type tags and round-trip structuring pass without the KeyError.
Written by the indexing model from the issue text.
Description
- cattrs version: 22.2.0
- Python version: 3.9
- Operating System: Ubuntu 20.04
Description
When you wrap a union type multiple times, e.g., Optional[list[Union[A, B]]], the custom unstructure function on the union type is not called. I believe this is related to https://github.com/python-attrs/cattrs/issues/129.
What I Did
import attrs
import cattrs
from typing import Optional, Union
c = cattrs.Converter()
@attrs.define
class A:
a: int
@attrs.define
class B:
a: int
@attrs.define
class C:
f: Optional[list[Union[A, B]]]
c.register_unstructure_hook(
Union[A, B],
lambda o: {"_type": o.__class__.__name__, **c.unstructure(o)},
)
c.register_structure_hook(
Union[A, B], lambda o, t: c.structure(o, A if o["_type"] == "A" else B)
)
inst = C([A(1), B(2)])
unstructured = c.unstructure(inst)
assert unstructured["f"][0]["_type"] == "A"
assert unstructured["f"][1]["_type"] == "B"
assert c.structure(unstructured, C) == inst
You should get the following error:
❯ python reproduce.py
Traceback (most recent call last):
File "/home/peter/programming/seagull/reproduce.py", line 34, in <module>
assert unstructured["f"][0]["_type"] == "A"
KeyError: '_type'
- Dominant language
- Python
- Stars
- 1.1k
- Forks
- 159
- Avg merge
- 12h 21m
- Merged PRs (30d)
- 6
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.
More from python-attrs/cattrs
-
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
python-attrs/cattrs#761 · 2 comments ·
-
Difficulty 2/5 1-3 hours Newbie friendliness 64/100
python-attrs/cattrs#513 · 4 comments ·
-
Difficulty 2/5 1-3 hours Newbie friendliness 35/100
python-attrs/cattrs#779 ·
-
Difficulty 3/5 1-2 days Newbie friendliness 85/100
python-attrs/cattrs#774 ·
-
Difficulty 5/5 Over a week Newbie friendliness 35/100
python-attrs/cattrs#746 · 2 comments ·
All issues in python-attrs/cattrs
Similar issues
-
Difficulty 2/5 1-3 hours Newbie friendliness 88/100
-
Difficulty 2/5 1-3 hours Newbie friendliness 82/100
-
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
-
enhancement
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
-
Difficulty 2/5 1-3 hours Newbie friendliness 74/100