Skip to content
New issue

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

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

Already on GitHub? # to your account

Require argument names to match in Protocol #18680

Open
sid-kap opened this issue Feb 14, 2025 · 3 comments
Open

Require argument names to match in Protocol #18680

sid-kap opened this issue Feb 14, 2025 · 3 comments

Comments

@sid-kap
Copy link
Contributor

sid-kap commented Feb 14, 2025

Feature

Currently mypy does not check that argument names in functions that implement protocols match the argument names in the protocol. This fails when arguments are passed as keywords.

For example, this passes mypy:

from typing import Protocol

class MyProtocol(Protocol):
    def foo(self, a: int) -> None: ...

class MyObject:
    def foo(self, b: int) -> None:
        pass

def call_foo(obj: MyProtocol) -> None:
    obj.foo(a=1)

call_foo(MyObject())

but fails at runtime:

Traceback (most recent call last):
  File "/Users/sidharthkapur/protocol_test.py", line 13, in <module>
    call_foo(MyObject())
  File "/Users/sidharthkapur/protocol_test.py", line 11, in call_foo
    obj.foo(a=1)
TypeError: MyObject.foo() got an unexpected keyword argument 'a'

Pitch

If we checked this in mypy, we could prevent runtime errors like the one above.

@sterliakov
Copy link
Collaborator

This seems to be a deliberate decision: only __call__ arg names are checked, other are explicitly ignored. But that dates to 2018, perhaps it's fine to get stricter now?

@erictraut
Copy link

FWIW, pyright has enforced this for many years. Plus, this is required by the Python typing spec and its conformance tests.

@A5rocks
Copy link
Collaborator

A5rocks commented Feb 16, 2025

This seems to be a deliberate decision: only __call__ arg names are checked, other are explicitly ignored. But that dates to 2018, perhaps it's fine to get stricter now?

Maybe we could implement it and see fallout in mypy primer.

# for free to join this conversation on GitHub. Already have an account? # to comment
Projects
None yet
Development

No branches or pull requests

4 participants