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)
?
What is a mixin in Python. A mixin is a class that provides method implementations for reuse by multiple related child classes. However, the inheritance is not implying an is-a relationship. A mixin doesn't define a new type.
Introduced since Python 3.5, Python's typing module attempts to provide a way of hinting types to help static type checkers and linters accurately predict errors.
Mixins encourage code reuse and can be used to avoid the inheritance ambiguity that multiple inheritance can cause (the "diamond problem"), or to work around lack of support for multiple inheritance in a language. A mixin can also be viewed as an interface with implemented methods.
Mixins are an alternative class design pattern that avoids both single-inheritance class fragmentation and multiple-inheritance diamond dependencies. A mixin is a class that defines and implements a single, well-defined feature. Subclasses that inherit from the mixin inherit this feature—and nothing else.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With