python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
17.85k stars 2.74k forks source link

False Negative when Enforcing Positional Arguments in regards to Protocols #17421

Open max-muoto opened 1 week ago

max-muoto commented 1 week ago

Bug Report

MyPy doesn't raise a warning if you pass in an class implementation that enforces positional arguments on a method, for a protocol that does not.

To Reproduce

Example of a false negative. Executing this code leads to a runtime error, as ActualReadable.read will raise an error when trying to pass in a key-word argument.

from typing import Protocol

class Readable(Protocol):
    def read(self, n: int = -1) -> bytes: ...

class ActualReadable:
    def read(self, n: int = -1, /) -> bytes:
        return b""

def foo(readable: Readable) -> None:
    readable.read(n=1)

foo(ActualReadable())

MyPy Playground

Expected Behavior

Pyright's behavior would be good to model off of in terms of expected behavior. That is, raising a warning that the implementation isn't compatible with the protocol, and that n must not be positional-only.

Pyright Playground

Your Environment