Skip to content

Instantly share code, notes, and snippets.

@PeterJCLaw
Created July 26, 2023 15:55
Show Gist options
  • Save PeterJCLaw/86536eac58349e2cbbd271c3593c2218 to your computer and use it in GitHub Desktop.
Save PeterJCLaw/86536eac58349e2cbbd271c3593c2218 to your computer and use it in GitHub Desktop.
Python protocol inheritance
from typing import Protocol
class IFoo(Protocol):
def bar(self) -> None:
...
class BaseFoo:
def bar(self) -> None:
print('base foo', type(self))
class Foo(IFoo):
pass
class ChildFooA(BaseFoo, IFoo):
pass
class ChildFooB(IFoo, BaseFoo):
pass
Foo().bar() # mypy(error): Cannot instantiate abstract class "Foo" with abstract attribute "bar" [abstract]
# does not print
BaseFoo().bar()
# prints: base foo <class '__main__.BaseFoo'>
ChildFooA().bar()
# prints: base foo <class '__main__.ChildFooA'>
ChildFooB().bar() # mypy(error): Cannot instantiate abstract class "ChildFooB" with abstract attribute "bar" [abstract]
# does not print
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment