与mypy的可比类型

时间:2017-12-25 01:28:12

标签: python python-3.x typechecking duck-typing 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

然而,mypy抱怨说:

error: Unsupported left operand type for <= ("T")

显然,输入模块并不允许我表达这一点(尽管将来可能会Comparable添加__eq__)。

我认为检查该对象是否具有__lt__和{{1}}方法(至少对于我的用例)就足够了。目前有没有办法在Python中表达这个要求,以便Mypy能够理解它?

1 个答案:

答案 0 :(得分:3)

经过一番研究,我找到了一个解决方案:协议。由于它们不是完全稳定的(但仍然是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)