Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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)])
like image 498
Tim Richardson Avatar asked Jan 12 '16 05:01

Tim Richardson


People also ask

How do you use type hints in Python?

Here's how you can add type hints to our function: Add a colon and a data type after each function parameter. Add an arrow ( -> ) and a data type after the function to specify the return data type.

How do you write a class hint in Python?

In a type hint, if we specify a type (class), then we mark the variable as containing an instance of that type. To specify that a variable instead contains a type, we need to use type[Cls] (or the old syntax typing. Type ).

What is collections OrderedDict?

An OrderedDict is a dictionary subclass that remembers the order in which its contents are added. import collections print 'Regular dictionary:' d = {} d['a'] = 'A' d['b'] = 'B' d['c'] = 'C' d['d'] = 'D' d['e'] = 'E' for k, v in d. items(): print k, v print '\nOrderedDict:' d = collections.

What is typing module in Python?

Introduced since Python 3.5, Python's typing module attempts to provide a way of hinting types to help static type checkers and linters accurately predict errors.


2 Answers

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]
like image 95
majkelx Avatar answered Oct 02 '22 09:10

majkelx


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__
like image 35
Kyle Strand Avatar answered Oct 02 '22 09:10

Kyle Strand