How can I define the type of SortedDict?
from typing import Dict
from sortedcontainers import SortedDict
x: Dict[int, str] = {2: "two"}
y: SortedDict[int, str] = {3: "three"} # <--- this doesn't work ...
I realize that the exact name SortedDict will not do as this is the actual class, but what will work?
$ python3.8 example.py
Traceback (most recent call last):
File "example.py", line 5, in <module>
y: SortedDict[int, str] = {3: "three"}
TypeError: 'type' object is not subscriptable
Since the original packages has no type information, what you can do is make your own interface stub like this:
(Notice I made the value type "sortable" so the type checker verifies you don't pass it a
list).Save this as
sortedcontainers.pyiand then set mypy's search path to it:Now you can do the following:
If you check it, you'll see that mypy catches the error:
Hope this helped.