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 OrderedDict
from typing import Dict

def 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).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)