Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python typing module: Mixin

Tags:

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)?

like image 534
Andras Gyomrey Avatar asked Jul 04 '17 18:07

Andras Gyomrey


People also ask

Does Python have mixin?

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.

What is typing module in Python?

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.

Why should we use mixin?

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.

How do Mixins work Python?

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.


1 Answers

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.

like image 121
Choi Geonu Avatar answered Oct 16 '22 17:10

Choi Geonu