Consider the following minimal example:
class A:
def f(self): pass
class B(A): pass
class C(A): pass
class D:
def g(self): pass
class E(B,D): pass
class F(C,D): pass
AandD = ...
def h(obj: AandD): pass
The class A
in my example can have a complex inheritance tree with many subclasses (B
, C
, etc.). I want that some instances of the subclasses of A
have additional functionality g
, so I introduced another class D
and used multiple inheritance to define E
and F
.
How to annotate properly the parameter obj
of the function h
, which should accept instances that inherit from A
and D
simultaneously, i.e., what should be instead of AandD
?
I know that I can define a protocol:
from typing import Protocol
class AandD(Protocol):
def f(self): pass
def g(self): pass
But I’d like to avoid repetitions in the code, since my classes contain a lot of methods. Also it won’t work for a Python version prior to 3.8.
I’d also like to avoid using Union[E,F]
, since it will force me to update the list everywhere in my code, if I add a new subclass of A
and D
.