No error reported when a contravariant TypeVar is used as a return type within a tuple
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
Mypy reports an error (as expected) when a contravariant TypeVar is used as a return type. However, if it is wrapped in a tuple, no error is reported (unexpected, I think). The same issue is present when using list here instead of tuple.
This issue is not present when using the 3.12+ type parameter syntax (i.e., the variance is inferred correctly as not-contravariant).
To Reproduce
from typing import TypeVar
T = TypeVar("T", contravariant=True)
def f(x: T) -> tuple[T]:
return (x,)
Expected Behavior
Mypy reports an error.
Actual Behavior
No error reported.
A longer reproducible example
- gist: https://gist.github.com/mypy-play/489aaad37715e215ecab49ee128553d5
- playground: https://mypy-play.net/?mypy=latest&python=3.13&flags=strict&gist=489aaad37715e215ecab49ee128553d5
This covers the contravariant variable being (i) used properly, (ii) used as output directly, (iii) wrapped in a tuple in the output, under the old and new typing syntaxes.
Environment
- Mypy version used: mypy 1.18.2 (compiled: yes)
- Mypy command-line flags:
--strict - Mypy configuration options from
mypy.ini(and other config files): N/A - Python version used: Python 3.13.8
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 with the minimal reproducer in the issue and run it with mypy's --strict settings, comparing direct, tuple, and list returns with the Python 3.12+ type-parameter cases described there. Done means mypy reports the expected error for the contravariant TypeVar in each applicable return form while preserving the newer syntax behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100