Skip to content

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

@prasanthcakewalk

Description

@prasanthcakewalk

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions