Unions of `TypedDict` turn into intersections in some generic functions
Open
Nobody has claimed this yet.
bug
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
When passing unions of TypedDict to certain generic functions, mypy deduces their type to be the intersection of the TypedDicts, and not the union.
Discovered here.
To Reproduce
from typing import TypedDict, TypeVar
class A(TypedDict):
shared: str
different: str
class B(TypedDict):
shared: str
different: int
extra: int
T = TypeVar("T")
def f(a: T, b: T) -> T:
return b
def g(a: T | None, b: T) -> T:
return b
c: A | B
d: A | B
r1: A | B = f(c, d) # passes
r2: A | B = g(c, d) # expression has type "TypedDict({'shared': str}) [assignment]
Expected Behavior
g(c, d) should have type A | B and not {"shared": str}.
Actual Behavior
mypy_error.py:23: error: Incompatible types in assignment (expression has type "TypedDict({'shared': str})", variable has type "Union[A, B]") [assignment]
Found 1 error in 1 file (checked 1 source file)
Your Environment
- Mypy version used: mypy 1.0.0 (compiled: yes)
- Same error on mypy 0.800, Python 3.10.9
- Mypy command-line flags: none
- Mypy configuration options from
mypy.ini(and other config files): none - Python version used: Python 3.10.9
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 by running the minimal Python reproducer from the issue and compare the inferred types of f(c, d) and g(c, d). Trace mypy's generic type inference for TypedDict unions, then add a regression test covering the example and confirm that g(c, d) is accepted as A | B.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 40/100