KEMBAR78
Problems with "expected overloaded function" when method hinted via Callback Protocol (⇝`numpy`) · Issue #18101 · python/mypy · GitHub
Skip to content

Problems with "expected overloaded function" when method hinted via Callback Protocol (⇝numpy) #18101

@randolf-scholz

Description

@randolf-scholz

Bug Report

mypy complains about expecting an overloaded function, when a method is hinted by a Callback-Protocol. This technique is used in the numpy stubs, and causes mypy to complain when trying to describe numpy scalars with simple protocols.

To Reproduce

Below is a MWE [mypy-playground], based on how the numpy stubs declare the methods on scalars. Note that [pyright-playground] does not report any issues.

from typing import Protocol, Self, overload

class NumpyFloat:
    __add__: "FloatOP"

class FloatOP(Protocol):
    @overload
    def __call__(self, other: float) -> NumpyFloat: ...
    @overload
    def __call__(self, other: NumpyFloat) -> NumpyFloat: ...

class SupportsAdd(Protocol):
    @overload
    def __add__(self, other: float) -> Self: ...
    @overload
    def __add__(self, other: NumpyFloat) -> Self: ...

x: SupportsAdd = NumpyFloat()  # expected overloaded function, got "FloatOP"

Concrete example with numpy==2.1.3 (again, pyright reports no errors):

from typing import Protocol, Self, overload
import numpy as np

class TimeDelta(Protocol):
    def __sub__(self, other: Self, /) -> Self: ...

class TimeStamp[TD: TimeDelta](Protocol):
    @overload
    def __sub__(self, other: Self, /) -> TD: ...
    @overload
    def __sub__(self, other: TD, /) -> Self: ...

x: TimeStamp[np.timedelta64] = np.datetime64("2021-01-01")  # ✅
y: TimeStamp[np.float64] = np.float64(10.0)  # expected overloaded function, got "_FloatOp[_64Bit]"

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