how to type hint collections.OrderedDict via python 3.5 typing module

删除回忆录丶 提交于 2019-12-04 22:34:29

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

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

(Note the extraneous parentheses around [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. So you can write:

from typing import OrderedDict
Movie = OrderedDict[Actor, Location]

or with backward compatibility workaround suggested by AChampion

try:
    from typing import OrderedDict
except ImportError:
    from typing import MutableMapping
    OrderedDict = MutableMapping
Movie = OrderedDict[Actor, Location]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!