与mypy可比类型

2024-04-25 23:17:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个泛型类来表示一个值有上下限,并执行这些边界。在

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抱怨说:

^{pr2}$

显然,键入module不允许我表达这一点(尽管它looks like添加{}可能在将来发生)。在

我认为检查对象是否有__eq__和{}方法就足够了(至少对于我的用例)。目前有没有任何方法可以用Python表达这个需求,以便Mypy能够理解它?在


Tags: 方法fromimportselftypingobjectanyoptional
1条回答
网友
1楼 · 发布于 2024-04-25 23:17:58

经过更多的研究,我找到了一个解决方案:协议。因为它们不是完全稳定的(Python3.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)

现在我们可以将我们的类型定义为:

^{pr2}$

我很高兴:

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)

相关问题 更多 >