Skip to content

Unexpected error using Union[] as the argument to the value field of a dictionary #19357

Closed as not planned
@sborisch

Description

@sborisch

Unexpected error using Union[] as the argument to the value field of a dictionary

Bug Report

Hello,

I am trying to use mypy to validate my use of type hints where I have a dictionary where the value fields in the dictionary can be either: str, bool, or int. That is:

Union[str,bool,int]

However, if I do this, I get

Incompatible types in assignment (expression has type "str | int | bool", variable has type "str") [assignment]

To Reproduce

Example code:

  flac_song_dict : dict[str,Union[str,int,bool]] 
  for (dummy_key,flac_song_dict) in flac_album_dict.items():

    flac_filename      : str = flac_song_dict["FILENAME"]  
    flac_ext           : str = flac_song_dict["FILEEXT"]   
    flac_track_num     : int = flac_song_dict["TRACK_NUM"] 
    flac_song          : str = flac_song_dict["SONG"]      
    flac_filepath      : str = flac_song_dict["FILEPATH"]    

to avoid this error, I need to change

  flac_song_dict : dict[str,Union[str,int,bool]] 

to
flac_song_dict : dict[str,any]

Expected Behavior

I would have expected the above to not produce an error.
IMO, the use of "any" is less optimal than Union[str,int,bool]

Actual Behavior

Incompatible types in assignment (expression has type "str | int | bool", variable has type "str") [assignment]

Your Environment

  • Mypy version used: 1.16.1
  • Mypy command-line flags (none):
  • Mypy configuration options from mypy.ini (and other config files): As far as I can tell, this file does not exist for me. I do not see it in the directory tree where mypy is installed.
  • Python version used: 3.10.12

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions