Search code examples
pythonmypypython-typing

Union of dict with typed keys not compatible with an empty dict


I'd like to type a dict as either a dictionary where the all the keys are integers or a dictionary where all the keys are strings.

However, when I read mypy (v0.991) on the following code:

from typing import Union, Any

special_dict: Union[dict[int, Any], dict[str, Any]]

special_dict = {}

I get an Incompatible types error.

test_dict_nothing.py:6: error: Incompatible types in assignment (expression has type "Dict[<nothing>, <nothing>]", variable has type "Union[Dict[int, Any], Dict[str, Any]]")  [assignment]
Found 1 error in 1 file (checked 1 source file)

How do I express my typing intent.


Solution

  • This is a mypy bug, already reported here with priority 1. There is a simple workaround suggested:

    from typing import Any
    
    special_dict: dict[str, Any] | dict[int, Any] = dict[str, Any]()
    

    This code typechecks successfully, because you basically give mypy a hint with more specific type of your dictionary. It may be any matching type and won't affect further checking, because you broaden the final type with an explicit type hint.