Decorator with constrained TypeVar specializes to first constraint
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
Changing the order of constraints of TypeVar T changes whether or not mypy passes. The wrapped method always gets narrowed to whatever the first constraint type is set to.
To Reproduce
from collections.abc import Callable
from typing import TypeVar, reveal_type
T = TypeVar("T", str, bytes) # fails
# T = TypeVar("T", bytes, str) # passes
def decorator(fn: Callable[[T], T]) -> Callable[[T], T]:
def wrapped(data: T) -> T:
return fn(data)
return wrapped
@decorator
def process(data: T) -> T:
return data
b: bytes = b"test"
result = process(b)
Or see mypy playground: https://mypy-play.net/?mypy=latest&python=3.12&gist=12fd2e05764d26a16cd1d16a10897671
Expected Behavior
Ideally pass for both versions, or consistently fail regardless of the constraint order.
On pyright playground the revealed types match my expectations and pass with either TypeVar order
Actual Behavior
mypy passes or fails depending on TypeVar constraint order, or the data input type
Your Environment
Same behavior with all tested mypy versions (1.6.0 .. 1.19.1) and python 3.11+
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 decorator and constrained TypeVar reproducer from the issue, then trace mypy's handling of constraint specialization and the wrapped callable. Done means the result no longer depends on the order of the TypeVar constraints, with coverage for both constraint orders.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100