我正在尝试创建一个泛型类来表示值具有下限和上限,并强制执行这些边界。
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
但是,mypy抱怨说:
error: Unsupported left operand type for <= ("T")
显然打字模块不允许我表达这一点(虽然它将来可能会发生looks like Comparable
)。
我认为检查该对象是否具有__eq__
和__lt__
方法(至少对于我的用例)就足够了。有没有办法在Python中表达这个要求,以便Mypy能理解它?
经过一番研究,我找到了一个解决方案:协议。由于它们并非完全稳定(但仍然是Python 3.6),因此必须从typing_extensions
模块导入它们。
import typing
from typing import Any
from typing_extensions import Protocol
from abc import abstractmethod
C = typing.TypeVar("C", bound="Comparable")
class Comparable(Protocol):
@abstractmethod
def __eq__(self, other: Any) -> bool:
pass
@abstractmethod
def __lt__(self: C, other: C) -> bool:
pass
def __gt__(self: C, other: C) -> bool:
return (not self < other) and self != other
def __le__(self: C, other: C) -> bool:
return self < other or self == other
def __ge__(self: C, other: C) -> bool:
return (not self < other)
现在我们可以将我们的类型定义为:
C = typing.TypeVar("C", bound=Comparable)
class Bounded(object):
def __init__(self, minValue: C, maxValue: C) -> None:
assert minValue <= maxValue
self.__minValue = minValue
self.__maxValue = maxValue
而且Mypy很高兴:
from functools import total_ordering
@total_ordering
class Test(object):
def __init__(self, value):
self.value = value
def __eq__(self, other):
return self.value == other.value
def __lt__(self, other):
return self.value < other.value
FBounded(Test(1), Test(10))
FBounded(1, 10)