如何通过 python 3.5 输入模块输入提示 collections.OrderedDict [英] how to type hint collections.OrderedDict via python 3.5 typing module
问题描述
我想使用 OrderedDict,其中键是 Enum,项目是某个类.
I want to use an OrderedDict where the key is a Enum and where the item is a certain class.
我如何使用打字模块来提示这一点?这个暗示的namedtuple的类比是什么::
How do I use the typing module to hint this? What is the analog to this hinted namedtuple::
Move = typing.NamedTuple('Move', [('actor', Actor), ('location', Location)])
推荐答案
如 AChampion 的评论中所述,您可以使用 MutableMapping
:
As noted in a comment by AChampion, you can use MutableMapping
:
class Actor(Enum):
# ...Actor enum menbers...
class Location:
# ...Location class body...
class MapActor2Location(OrderedDict, MutableMapping[Actor, Location]):
pass
<小时>
针对像我这样以前没有使用过 typing
模块的人的附录:注意类型定义使用索引语法 ([T]
) without 括号.我最初尝试过这样的事情:
Addendum for people like me who haven't used the typing
module before: note that the type definitions use indexing syntax ([T]
) without parentheses. I initially tried something like this:
class MyMap(OrderedDict, MutableMapping([KT, VT])): pass
(注意[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__
这篇关于如何通过 python 3.5 输入模块输入提示 collections.OrderedDict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!