python / python/mypy

Bug: overloads not matched when using `TypeVar` with `default` (where Pyright matches correctly)

Open
#19,182 8 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-calls topic-pep-696
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

In the example below, mypy reveals the type to be Any, whereas Pyright correctly detects Bar

Note that replacing T | None with T makes Mypy also infer the type correctly

Noticed while working on pandas-stubs

To Reproduce

from typing import Any, Callable, Generic, Protocol, Self, overload, reveal_type

from typing_extensions import TypeVar

T = TypeVar("T", bound=str | int, default=Any)


class Foo(Generic[T]):
    def __init__(self, t: T) -> None:
        self.t = t


class Bar(Protocol):
    @overload
    def apply(self, f: Callable[..., Foo]) -> Self: ...
    @overload
    def apply(self, f: Callable[..., T | None]) -> Foo[T]: ...


def func() -> Foo:
    return Foo(3)


def main(b: Bar) -> None:
    reveal_type(b.apply(func))

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

Expected Behavior

that reveal_type would show Bar (for reference, this is what Pyright does)

Actual Behavior

note: Revealed type is "Any"

Your Environment

  • Mypy version used: 1.15.0
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.12

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

The issue names no source file or test. Start with the supplied Python 3.12 reproduction, run it with mypy 1.15.0, and compare the reveal_type result with Pyright; done means the overload resolves to Bar instead of Any for this case.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.