Skip to content

Instantly share code, notes, and snippets.

@PeterJCLaw
Created July 26, 2023 15:55
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