[英]how to type hint collections.OrderedDict via python 3.5 typing module
I want to use an OrderedDict where the key is a Enum and where the item is a certain class. 我想使用一个OrderedDict,其中键是一个枚举,并且该项是某个类。
How do I use the typing module to hint this? 我如何使用输入模块来暗示这一点? What is the analog to this hinted namedtuple:: 什么是这个暗示的namedtuple ::
Move = typing.NamedTuple('Move', [('actor', Actor), ('location', Location)])
As noted in a comment by AChampion, you can use MutableMapping
: 如AChampion的评论中所述,您可以使用MutableMapping
:
class Actor(Enum):
# ...Actor enum menbers...
class Location:
# ...Location class body...
class MapActor2Location(OrderedDict, MutableMapping[Actor, Location]):
pass
Addendum for people like me who haven't used the typing
module before: note that the type definitions use indexing syntax ( [T]
) without parentheses. 像我这样以前没有使用过typing
模块的人的附录:注意类型定义使用没有括号的索引语法( [T]
)。 I initially tried something like this: 我最初尝试过这样的事情:
class MyMap(OrderedDict, MutableMapping([KT, VT])): pass
(Note the extraneous parentheses around [KT, VT]
!) (注意[KT, VT]
周围的无关括号!)
This gives what I consider a rather confusing error: 这给了我认为是一个相当混乱的错误:
TypeError: Can't instantiate abstract class MutableMapping with abstract methods __delitem__, __getitem__, __iter__, __len__, __setitem__
The question is about 3.5, but typing.OrderedDict
was introduced in the python 3.7.2 . 问题是大约3.5,但是在Python 3.7.2中引入了 typing.OrderedDict
。 So you can write: 所以你可以写:
from typing import OrderedDict
Movie = OrderedDict[Actor, Location]
or with backward compatibility workaround suggested by AChampion 或者使用AChampion建议的向后兼容性解决方法
try:
from typing import OrderedDict
except ImportError:
from typing import MutableMapping
OrderedDict = MutableMapping
Movie = OrderedDict[Actor, Location]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.