python 无法定义 SortedDict 类型

python type of SortedDict can not be defined

如何定义 SortedDict 的类型?

from typing import Dict
from sortedcontainers import SortedDict

x: Dict[int, str] = {2: "two"}
y: SortedDict[int, str] = {3: "three"} # <--- this doesn't work ...

我意识到确切的名称 SortedDict 不会起作用,因为这是实际的 class,但是 起作用吗?

$ python3.8 example.py 
Traceback (most recent call last):
  File "example.py", line 5, in <module>
    y: SortedDict[int, str] = {3: "three"}
TypeError: 'type' object is not subscriptable

由于原始包没有类型信息,您可以做的是像这样制作自己的接口存根:

from typing import Any, Dict, Hashable, Iterable, Optional, Protocol, Tuple, TypeVar

class Comparable(Protocol):
    def __lt__(self, other: Any) -> bool: ...

K = TypeVar("K", bound=Hashable)
V = TypeVar("V", bound=Comparable)

class SortedDict(Dict[K, V]):
    def bisect_left(self, value: V) -> int: ...
    def bisect_right(self, value: V) -> int: ...
    def index(
        self, value: V, start: Optional[int] = None, stop: Optional[int] = None
    ) -> int: ...
    def irange(
        self,
        minimum: Optional[V] = None,
        maximum: Optional[V] = None,
        inclusive: Tuple[bool, bool] = (True, True),
        reverse: bool = False,
    ) -> Iterable[V]: ...
    def islice(
        self,
        start: Optional[int] = None,
        stop: Optional[int] = None,
        reverse: bool = False,
    ) -> Iterable[V]: ...

(注意我将值类型设置为“可排序”,因此类型检查器会验证您没有将其传递给 list)。

将其保存为 sortedcontainers.pyi,然后将其设置为 mypy's search path

MYPYPATH=/path/to/interfaces mypy <args...>

现在您可以执行以下操作:

# example.py
from __future__ import annotations

from typing import Dict, Optional

from sortedcontainers import SortedDict

x: Dict[int, str] = {2: "two"}
y = SortedDict({3: "three"})
def foo(z: SortedDict[int, str]) -> Optional[str]:
    if 3 in z:
        z_3 = z[3]
        if isinstance(z_3, str):
            return z_3
    return None
t = foo(x) # <--- x is not a SortedDict
if t:
    print(t)

如果你检查它,你会看到 mypy 捕获错误:

$ mypy example.py
example.py:16: error: Argument 1 to "foo" has incompatible type "Dict[int, str]"; expected "SortedDict[int, str]"
Found 1 error in 1 file (checked 1 source file)

希望对您有所帮助。