Skip to content

The variadic parameter (TypeVarTuple) of a generic type alias can be covariant and contravariant whether a new or old syntax against the doc "always invariant"  #20498

@hyperkai

Description

@hyperkai

*Memo:

  • mypy test.py
  • mypy 1.19.1
  • Python 3.14.0
  • Windows 11

The doc says a variadic parameter (TypeVarTuple) is always invariant as shown below:

  1. If the type parameter is variadic (TypeVarTuple) or a parameter specification (ParamSpec), it is always considered invariant. No further inference is needed.

But the variadic parameter (TypeVarTuple) of a generic type alias can be covariant and contravariant whether a new or old syntax against the doc "always invariant" as shown below:

from collections.abc import Callable
# from typing import TypeVarTuple, TypeAlias, Unpack

''' New syntax '''
type TA1[*Ts] = tuple[*Ts]            # Covariant
type TA2[*Ts] = Callable[[*Ts], None] # Contravariant
''' New syntax '''

''' Old syntax '''
# Ts = TypeVarTuple('Ts')

# TA1: TypeAlias = tuple[Unpack[Ts]]            # Covariant
# TA2: TypeAlias = Callable[[Unpack[Ts]], None] # Contravariant
''' Old syntax '''

class A: ...
class B(A): ...
class C(B): ...
class D(C): ...
class E(D): ...

v1: TA1[C, C] = (C(), C())

# Covariant
a1: TA1[A, A] = v1 # No error
b1: TA1[B, B] = v1 # No error
c1: TA1[C, C] = v1 # No error
d1: TA1[D, D] = v1 # Error
e1: TA1[E, E] = v1 # Error

v2: TA2[C] = lambda x: None

# Contravariant
a2: TA2[A] = v2 # Error
b2: TA2[B] = v2 # Error
c2: TA2[C] = v2 # No error
d2: TA2[D] = v2 # No error
e2: TA2[E] = v2 # No error

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions