python typing module: Mixin
Is there any class under typing
that behaves like a mixin?
For example
from typing import Union
class A:
pass
class B:
pass
class C:
pass
class D(A, B, C):
pass
# current: ab is A or B, but not both
def f(ab: Union[A, B]):
pass
# ideal: ab is A and B
def f(ab: Mixin[A, B]):
pass
f(D())
please notice how D
is instance of A
and B
, but also C
. This would be too much of a restriction for f
(since f
doesn't require C
) and thus, the parameter ab
is not necessarily of type D
but Mixin[A, B]
If the typing
module doesn't provide any option, is there anything more elegant than creating my own class AB(A, B)
?
Solution 1:
It seem to be impossible for now.
You can find a discussion about "Intersection" type in python/typing#123 repository.
There is a similar feature on PEP-544 called Protocol, and you can merge mixins by merging mixin protocols. There is an implementation of PEP-544 called typing_extensions. Maybe you can try that with this library.