python / python/mypy

False positive with variable key in Mapping with Optional value

Open
#10,163 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

When using a mapping with an Optional value type, accessing a value using a variable key instead of a literal key prevents a None check from working properly.

To Reproduce

  1. Put the following code in test.py:
from typing import Mapping, Optional

FOO: str = "foo"

def func(text: str) -> None:
    _ = text

data: Mapping[str, Optional[str]] = {FOO: "bar"}

if data[FOO] is not None:
    func(data[FOO])  # Line 11

if data["foo"] is not None:
    func(data["foo"])
  1. Run mypy test.py

Expected Behavior

mypy should not output any errors. As the above example shows, using a string literal instead of a variable containing a string does not cause any errors, even though the code is otherwise identical. The "Optional types and the None type" section of the documents says "supported checks for guarding against a None value include if x is not None", so this code should work.

Actual Behavior

mypy outputs the following:

test.py:11: error: Argument 1 to "func" has incompatible type "Optional[str]"; expected "str"  [arg-type]

Your Environment

  • Mypy version used: 0.812
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): show_error_codes = True
  • Python version used: 3.7.9
  • Operating system and version: macOS 10.15.7 (19H524)

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 with the reproducer in test.py and run mypy test.py to confirm the variable-key and literal-key cases differ. Trace the type-checking path for Mapping access and Optional narrowing, then add a regression test covering the variable-key case. Done means both guarded calls type-check without errors.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers, devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.