Skip to content

Treat methods on protocols with empty bodies as abstract #8395

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

Closed
JarnoRFB opened this issue Feb 12, 2020 · 1 comment
Closed

Treat methods on protocols with empty bodies as abstract #8395

JarnoRFB opened this issue Feb 12, 2020 · 1 comment

Comments

@JarnoRFB
Copy link

When declaring a protocol it is suggested in the documentation that method that have to be defined in implementations of that protocol can be marked with ... and I find this syntax quite pretty. However, currently the ... is treated as a default implementation. Which can lead to confusing behavior. An example is the following:

from typing_extensions import Protocol


class SupportsAdding(Protocol):
    def add(self, x: int, y: int) -> int: ...


class Adder(SupportsAdding):
    def subtract(self, x: int, y: int) -> int:
        return x + y


if __name__ == '__main__':
    adder: SupportsAdding = Adder()
    z = adder.add(1, 2)
    print(type(z))
    reveal_type(z)

Given the rather drastic misspelling of add as subtract, mypy still infers the protocol to be correctly implemented. The result of reveal_type(z) is int, while it is actually NoneType. PEP 544 recommends to decorate non-default implementations with @abstractmethod. However, this leads to less elegant code and additional runtime checks. Since it seems kind of obvious that ... is never a default implementation of a method, I would suggest to treat it the same way as protocol methods decorated with @abstractmethod.

I am using mypy version 0.761.

@ilevkivskyi
Copy link
Member

This is essentially a particular case of #2350

(Btw I wanted to fix this at some point but decided it is not worth it)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants