如何通过 python 3.5 打字模块输入提示 collections.OrderedDict
how to type hint collections.OrderedDict via python 3.5 typing module
我想使用一个 OrderedDict,其中的键是一个枚举,其中的项目是某个 class。
如何使用输入模块来提示这一点?
这个暗示的 namedtuple::
的模拟是什么
Move = typing.NamedTuple('Move', [('actor', Actor), ('location', Location)])
如 AChampion 的评论所述,您可以使用 MutableMapping
:
class Actor(Enum):
# ...Actor enum menbers...
class Location:
# ...Location class body...
class MapActor2Location(OrderedDict, MutableMapping[Actor, Location]):
pass
像我这样以前没有使用过 typing
模块的人的附录:请注意类型定义使用索引语法 ([T]
) without括弧。我最初尝试过这样的事情:
class MyMap(OrderedDict, MutableMapping([KT, VT])): pass
(注意 [KT, VT]
周围的多余括号!)
这给出了我认为相当混乱的错误:
TypeError: Can't instantiate abstract class MutableMapping with abstract methods __delitem__, __getitem__, __iter__, __len__, __setitem__
问题是关于 3.5,但是 typing.OrderedDict
是 introduced in the python 3.7.2。所以你可以这样写:
from typing import OrderedDict
Movie = OrderedDict[Actor, Location]
或使用 AChampion
建议的向后兼容解决方法
try:
from typing import OrderedDict
except ImportError:
from typing import MutableMapping
OrderedDict = MutableMapping
Movie = OrderedDict[Actor, Location]
我想使用一个 OrderedDict,其中的键是一个枚举,其中的项目是某个 class。
如何使用输入模块来提示这一点? 这个暗示的 namedtuple::
的模拟是什么Move = typing.NamedTuple('Move', [('actor', Actor), ('location', Location)])
如 AChampion 的评论所述,您可以使用 MutableMapping
:
class Actor(Enum):
# ...Actor enum menbers...
class Location:
# ...Location class body...
class MapActor2Location(OrderedDict, MutableMapping[Actor, Location]):
pass
像我这样以前没有使用过 typing
模块的人的附录:请注意类型定义使用索引语法 ([T]
) without括弧。我最初尝试过这样的事情:
class MyMap(OrderedDict, MutableMapping([KT, VT])): pass
(注意 [KT, VT]
周围的多余括号!)
这给出了我认为相当混乱的错误:
TypeError: Can't instantiate abstract class MutableMapping with abstract methods __delitem__, __getitem__, __iter__, __len__, __setitem__
问题是关于 3.5,但是 typing.OrderedDict
是 introduced in the python 3.7.2。所以你可以这样写:
from typing import OrderedDict
Movie = OrderedDict[Actor, Location]
或使用 AChampion
建议的向后兼容解决方法try:
from typing import OrderedDict
except ImportError:
from typing import MutableMapping
OrderedDict = MutableMapping
Movie = OrderedDict[Actor, Location]