python / python/mypy

False Positive when assigning to union type as dictionary key

Open
#17,721 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

When defining a dictionary where the values are of type Union[dict, None]/Optional[dict]/dict | None and then using a conditional to confirm that the value is a dictionary before index assignment, mypy incorrectly reports that the index assignment is not valid with the following error message:

Unsupported target for indexed assignment ("dict[str, int | float] | None")

To Reproduce

https://gist.github.com/mypy-play/89bae9639af70dd72064b748098e54c5

Expected Behavior

Mypy recognizes that, due to the conditional and the assignment to an empty dict within the conditional scope, that the value is not None and is in fact an empty dictionary and does not raise a type error.

Actual Behavior
Mypy is unable to recognize that the type of the value is not None and raises a type error.

Your Environment

  • Mypy version used: 1.11.1
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.12.0

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the linked mypy-play reproduction with mypy 1.11.1 on Python 3.12 and confirm the reported indexed-assignment error. Trace the type-checking path for the conditional assignment to determine where the non-None dictionary type is lost; done means the reproduction no longer reports this error and related checks remain correct.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers, tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.