Search code examples
pythonpython-typingmypy

key typechecking in mypy Dict type


I recently started using mypy. Is there a way I can typecheck on Dic keys in mypy.

For ex).

from __future__ import annotations
from typing import List, Set, Dict, Tuple, Optional 
import sys


adj_list: Dict[int,List[int]] = {} 

if "x" not in adj_list.keys():
    print('Not found') 

The above code doesn't show any mypy warnings. In the following code I'm comparing a string object with Dictionary key which can only hold a int key. Is there a way mypy can warn about this invalid comparison


Solution

  • Yes -- use the --strict-equality flag. If you enable this flag, mypy will produce the following error:

    test.py:8: error: Non-overlapping container check (element type: "str", container item type: "int")
    

    You can find more information about this flag near the bottom of the Miscellaneous strictness options section in the mypy docs about command line flags it supports.

    There are many more strictness flags you can enable, if you prefer more stricter typechecking -- using the --strict flag will enable most of them. (Though not the --strict-equality flag, which must be configured separately.