简体   繁体   English

在python中提示类型

[英]type hinting in python

i have some problem to put type hinting in my python program. 我在将类型提示放入python程序时遇到一些问题。 it is from python 3.5. 它来自python 3.5。

With this example: 在此示例中:

# -*- 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__()

when i run mypy, i have the following: 当我运行mypy时,我有以下内容:

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

the thing i don't understand is why i have those errors. 我不明白的是为什么我有那些错误。

OrderedDict is not a subclass of typing.Generic and therefore cannot be parametrized. OrderedDict不是类型的子类。 typing.Generic ,因此无法参数化。 However you may easily define the corresponding type as follows: 但是,您可以轻松定义相应的类型,如下所示:

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)

You may then use it in all type hints : OrderedDictType[str,XV] instead of OrderedDict[str,XV] . 然后,您可以在所有类型提示中使用它: OrderedDictType[str,XV]而不是OrderedDict[str,XV]

See https://docs.python.org/3/library/typing.html#user-defined-generic-types and typing.py source for details and examples (I used the typing.List class as an example). 有关详细信息和示例,请参见https://docs.python.org/3/library/typing.html#user-defined-generic-typestyping.py源(我以typing.List类为例)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM