python-attrs / python-attrs/cattrs

Custom unstructure function is not called when a union type is wrapped in generic types multiple times

Open
#336 3 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

  • 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'

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 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.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.