与 mypy 的比较类型

2024-02-26

我正在尝试创建一个泛型类来表示一个值具有下限和上限,并强制执行这些界限。

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")

显然,打字模块不允许我表达这一点(尽管它好像 https://github.com/python/typing/issues/59 adding Comparable将来可能会发生)。

我认为检查该对象已经足够了__eq__ and __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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

与 mypy 的比较类型 的相关文章

随机推荐