I'm trying to create a generic class to express that a value has lower and upper bounds, and to enforce those bounds.
from typing import Any, Optional, TypeVar
T = TypeVar("T")
class Bounded(object):
def __init__(self, minValue: T, maxValue: T) -> None:
assert minValue <= maxValue
self.__minValue = minValue
self.__maxValue = maxValue
However, mypy complains that:
error: Unsupported left operand type for <= ("T")
Apparently typing module doesn't allow me to express this (although it looks like adding Comparable
might happen in the future).
I think it would be enough to check that object has __eq__
and __lt__
methods (for my use case at least). Is there any way to currently express this requirement in Python so that Mypy would understand it?
After a bit more research, I found a solution: Protocols. Since they are not fully stabile (yet of Python 3.6), they have to be imported from the
typing_extensions
modules.Now we can define our type as:
And Mypy is happy: