python-attrs / python-attrs/cattrs

Type Error with tagged Unions (working code but mypy/pyright error)

Open
#690 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

typeform
Dominant language
Python
Stars
1.1k
Forks
159
Avg merge
12h 21m
Merged PRs (30d)
6

Description

functionally this code does what I expect it to (asserts go through) but there is a type error in the signature of Converter.structure, it accepts cl: type[T] and UnionType does not match that

from typing import Literal, Union
from dataclasses import dataclass
import cattrs


@dataclass
class Add:
    t: Literal["ADD"]
    v: int


@dataclass
class Sub:
    t: Literal["SUB"]
    v: int


Op = Union[Add, Sub]
Op2 = Add | Sub

assert cattrs.structure(dict(t="ADD", v=10), Op) == Add(t="ADD", v=10)
assert cattrs.structure(dict(t="SUB", v=5), Op2) == Sub(t="SUB", v=5)

if I change this https://github.com/python-attrs/cattrs/blob/main/src/cattrs/converters.py#L587 to

     def structure(self, obj: UnstructuredValue, cl: type[T] | UnionType) -> T:

the type error goes away but I'm not sure if that is the right solution

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 src/cattrs/converters.py around the structure signature at line 587, then reproduce the example with mypy and pyright. Check that the annotation accepts both typing.Union and the | form while preserving the shown cattrs.structure assertions; done means the type errors are gone without changing runtime behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend-api-design
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
52/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.