Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding a field to a callback protocol changes the checks performed by mypy #17179

Open
vxgmichel opened this issue Apr 26, 2024 · 0 comments
Open
Labels
bug mypy got something wrong

Comments

@vxgmichel
Copy link

I noticed something really weird about callback protocols. Consider the following example:

from typing import TypeVar, Protocol


T = TypeVar("T")


class MyCallable(Protocol[T]):
    __name__: str

    def __call__(
        self,
        __arg: T,
    ) -> T: ...


def decorator(x: MyCallable[T]) -> MyCallable[T]:
    return x


@decorator
def func(arg: T) -> T:
    return arg


x = func(1)

It works fine with mypy 1.10.0 (although it fails to check with pyright 1.1.360: microsoft/pyright#7782).

However, adding a __name__: str field to the protocol changes the checks performed by mypy. The example becomes:

from typing import TypeVar, Protocol


T = TypeVar("T")


class MyCallable(Protocol[T]):
    __name__: str

    def __call__(
        self,
        __arg: T,
    ) -> T: ...


def decorator(x: MyCallable[T]) -> MyCallable[T]:
    return x


@decorator
def func(arg: T) -> T:
    return arg


x = func(1)

And it fails with:

test.py:25: error: Need type annotation for "x"  [var-annotated]
test.py:25: error: Argument 1 to "__call__" of "MyCallable" has incompatible type "int"; expected Never  [arg-type]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

1 participant