在python中键入提示

时间:2016-11-03 23:02:51

标签: python type-hinting

我在我的python程序中输入类型提示有一些问题。 它来自python 3.5。

通过这个例子:

# -*- coding: utf-8 -*-
import collections
import typing

XV = typing.TypeVar('XV')


class Coll(collections.OrderedDict[str, XV]):

    def sorted(self) -> collections.OrderedDict[str, XV]:
        dict_sorted = collections.OrderedDict()  # type: collections.OrderedDict[str,XV]
        for key in sorted(self.keys()):
            dict_sorted[key] = self[key]
        return dict_sorted

    def __str__(self) -> str:
        retour = ""  # type:str
        if len(self) == 0:
            return ""
        test = self.sorted()  # type: collections.OrderedDict[str,XV]
        for l in test:
            if retour:
                retour += "\n{0!s}".format(self[l])
            else:
                retour = "{0!s}".format(self[l])
        return retour

    def __repr__(self) -> str:
        return self.__str__()

当我运行mypy时,我有以下内容:

example.py:8: error: Invalid type "example.XV"
example.py: note: In function "__str__":
example.py:20: error: Invalid type "example.XV"

我不明白的是我有这些错误的原因。

1 个答案:

答案 0 :(得分:1)

OrderedDict不是typing.Generic的子类,因此无法进行参数化。但是,您可以按如下方式轻松定义相应的类型:

from typing import MutableMapping, TypeVar
from collections import OrderedDict

KT = TypeVar('KT')  # Key type.
VT = TypeVar('VT')  # Value type.

class OrderedDictType(OrderedDict, MutableMapping[KT, VT], extra=OrderedDict):
    __slots__ = ()

    def __new__(cls, *args, **kwds):
        raise TypeError("Type OrderedDictType cannot be instantiated;" +
                        " use OrderedDict() instead")

# isinstance check
a = OrderedDict()
assert isinstance(a, OrderedDictType)

然后,您可以在所有类型提示中使用它:OrderedDictType[str,XV]而不是OrderedDict[str,XV]

参见https://docs.python.org/3/library/typing.html#user-defined-generic-typestyping.py源代码以获取详细信息和示例(我以typing.List类为例)。