Created
May 30, 2020 19:53
-
-
Save pauleveritt/7fb13eea90ece7012b47535236f459ed to your computer and use it in GitHub Desktop.
PEP 544 protocols, implementing via subclass, and checking.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Example of "Explicitly declaring implementation" | |
PEP 544 says you can state that an implementation supports a protocol by | |
`subclassing the protocol <https://www.python.org/dev/peps/pep-0544/#explicitly-declaring-implementation>`_. | |
It also says: "If one omits Protocol in the base class list, this would | |
be a regular (non-protocol) class that must implement Sized." | |
In the implementation below, ``FrenchPerson`` says that it implements | |
``Person``. But it doesn't. And yet, ``mypy`` reports no errors. Not on | |
the definition nor when passing an instance to ``print_person``, which | |
asks for a ``Person``. | |
Are there any ``mypy`` checks for "must implement [the protocol]" as | |
stated in the PEP? | |
""" | |
from typing import Protocol | |
class Person(Protocol): | |
first_name: str | |
def greeting(self, message: str) -> str: | |
... | |
class FrenchPerson(Person): | |
prenom: str | |
def __init__(self, name: str): | |
self.prenom = name | |
def salutation(self, message: str) -> str: | |
return f"{message} {self.prenom}" | |
def print_person(person: Person) -> str: | |
return person.greeting(message="Je m'appelle") | |
def main(): | |
fp = FrenchPerson(name='Henri') | |
response = print_person(fp) | |
print(response) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment