Relative Content

Tag Archive for pythonmypypython-typing

Typing list[T] that allows T and derived classes Python MyPy

There is a problem that I have come across in python that the List type is invariant – meaning that it can only hold objects of a specific type or you will get a type error (for example when running mypy) – but sometimes you need to use a collection in a more generic function which can accept all types of a base class (lets call it A) as well as all derived classes. A clear example is this

Typing with protocol with generic typed variable

I’m trying to create a Mixin that assumes the child class has a certain variable that is of a generic type.
I use a Protocol to define that constraint on the mixin but mypy doesn’t seem to be able to resolve it.
Here is the most minimal version of my could I could get that reproduces the issue: