2016-11-03 64 views
0

我有一些问题,把类型暗示在我的python程序。 它来自python 3.5。类型暗示python

有了这个例子:

# -*- 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

'collections.OrderedDict'不带类型参数。 – user2357112

回答

0

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类作为示例)。