How do I specify OrderedDict K,V types for Mypy type annotation? How do I specify OrderedDict K,V types for Mypy type annotation? python python

How do I specify OrderedDict K,V types for Mypy type annotation?


There is no problem in mypy (at least, not in 0.501).But there is a problem with Python 3.6.0.Consider the following:

from collections import OrderedDictfrom typing import Dictdef foo() -> Dict[str, int]:    result: OrderedDict[str, int] = OrderedDict()    result['two'] = 2    return result

This code will both satisfy mypy (0.501) and Python (3.6.0).However, if you replace Dict with OrderedDict, then mypy will still be happy, but executing it will die with TypeError: 'type' object is not subscriptable.

It is interesting that the Python interpreter dies on seeing a subscripted OrderedDict in the function signature, but is happy to accept it in a variable type annotation.

At any rate, my workaround for this is to use Dict instead of OrderedDict in the function signature (and add a comment that this should be fixed if/when the Python interpreter will learn to accept the correct signature).


As a workaround, you can also put the return type into a string to satisfy both Mypy and Python 3.6:

from collections import OrderedDictdef foo() -> 'OrderedDict[str, int]':    result = OrderedDict()    result['foo'] = 123    return result


What you can also try is using MutableMapping (like in this Answer: https://stackoverflow.com/a/44167921/1386610)

from collections import OrderedDictfrom typing import Dictdef foo() -> MutableMapping[str, int]:    result = OrderedDict() # type: MutableMapping[str, int]    result['foo'] = 123    return result