Skip to content

Instantly share code, notes, and snippets.

@pauleveritt
Created May 30, 2020 19:53
Show Gist options
  • Save pauleveritt/7fb13eea90ece7012b47535236f459ed to your computer and use it in GitHub Desktop.
Save pauleveritt/7fb13eea90ece7012b47535236f459ed to your computer and use it in GitHub Desktop.
PEP 544 protocols, implementing via subclass, and checking.
"""
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