python / python/mypy

No error reported when a contravariant TypeVar is used as a return type within a tuple

Open
#20,273 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-type-variables
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

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

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.