Skip to content

Using Generic and __new__ in class def, mypy misses incorrect parameter if parameter created inline #14009

Description

@Dr-Irv

Bug Report

This came up in pandas-stubs, issue pandas-dev/pandas-stubs#412

If you have a stub that defines a Generic class with __new__(), with overloads, and the final overload doesn't specify the type of the generic, then a function call that creates an object of the generic class in the function call is not picked up as an error, but it is picked up if stored in another variable.

To Reproduce

Two files are needed. First is gptst2.pyi :

from typing import Generic, TypeVar, Type, overload

TV = TypeVar("TV", int, str)

class Foo(Generic[TV]):
    @overload
    def __new__(cls, ty: Type[TV]) -> Foo[TV]: ...
    @overload
    def __new__(cls, ty=...) -> Foo: ...

Then the tester code genparam.py:

from gptst2 import Foo


def fun(param: Foo[int]) -> Foo[str]:
    ...


fun(param=Foo(str))
p = Foo(str)
fun(p)

Expected Behavior

mypy should report errors on both calls to fun()

Actual Behavior
mypy does not pick up that the first call to fun is incorrect. It does pick up that the second call is incorrect.
pyright picks up both as being incorrect.

Output from mypy:

genparam.py:10: error: Argument 1 to "fun" has incompatible type "Foo[str]"; expected "Foo[int]"

Your Environment

  • Mypy version used: 0.971
  • Mypy command-line flags: --no-incremental
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.10

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-type-contextType context / bidirectional inference
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions