how to type hint collections.OrderedDict via pytho

2019-04-18 07:08发布

问题:

I want to use an OrderedDict where the key is a Enum and where the item is a certain class.

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)])

回答1:

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__