Han*_*ila 5 python duck-typing typechecking python-3.x mypy
我正在尝试创建一个泛型类来表示一个值具有下限和上限,并强制执行这些边界。
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
Run Code Online (Sandbox Code Playgroud)
但是,mypy 抱怨说:
error: Unsupported left operand type for <= ("T")
Run Code Online (Sandbox Code Playgroud)
显然,输入模块不允许我表达这一点(尽管看起来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)
Run Code Online (Sandbox Code Playgroud)
现在我们可以将我们的类型定义为:
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
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)