Skip to content

Better binding with implicit type variables #19367

Open
@randolf-scholz

Description

@randolf-scholz

Code sample in mypy playground

type Pair[T] = tuple[T, T]

class Foo[P: Pair]:
    def __init__(self, pair: P) -> None:
        self.pair: P = pair

foo = Foo((1, "a"))
reveal_type(foo)  # Foo[tuple[int, str]] ❌
reveal_type(foo.pair)  # tuple[int, str] ❌

In the example above, P gets bound to tuple[L[1], L["a"]], but this does not look like a Pair! My expectation was to get something like Foo[tuple[int | str, int | str]] or Foo[tuple[object, object]] or an arg-type error.

Indeed, we can get this inference if we put in some extra work: Code sample in mypy playground

class Bar[P: Pair]:
    def __init__[S](self: "Bar[Pair[S]]", pair: tuple[S, S]) -> None:
        self.pair: P = pair

bar = Bar((1, "a"))
reveal_type(bar)  # Bar[tuple[object, object]] ✅
reveal_type(bar.pair)  # tuple[object, object] ✅

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongquestiontopic-inferenceWhen to infer types or require explicit annotations

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions