Skip to content

Generic type aliases with TypeVar defaults infer to an incorrect type #18188

@alexdrydew

Description

@alexdrydew

Bug Report

When using type alias of a generic type which uses type variables with defaults unbound type variables may infer to an incorrect default type.

To Reproduce

from typing import Generic, TypeVar, TypeAlias

T1 = TypeVar('T1', default=int | None)
T2 = TypeVar('T2', default=int | None)

class A(Generic[T1, T2]):
    def __init__(self, a: T1, b: T2) -> None:
        self.a = a
        self.b = b


MyA: TypeAlias = A[T1, int]
a: MyA = A(None, 10)

https://mypy-play.net/?mypy=latest&python=3.12&gist=abece06adfb80e28c6d23bd99997964e

Expected Behavior

MyA should preserve T1 default type, which is int | None

Actual Behavior

T1 is inferred to int default in MyA, so assignment to a fails with:

Argument 1 to "A" has incompatible type "None"; expected "int" [arg-type]

Your Environment

  • Mypy version used: 1.13
  • Python version used: 3.12

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