python / python/mypy

Type refinements are not applied to index expressions

Open
#7,339 6 comments 6 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

false-positive feature priority-1-normal topic-type-narrowing
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Ran into this issue today, I believe mypy is incorrectly flagging this as an error:

from typing import Any, Dict, Optional


def rename_keys(
    original_dict: Dict[str, Any], key_mapping: Dict[str, Optional[str]]
) -> Dict[str, Any]:
    """Renames keys in the dictionary using the key_mapping. If the value in key_mapping is None then it will remove the key entirely"""
    return {
        key_mapping.get(k, k): v
        for k, v in original_dict.items()
        if k not in key_mapping or key_mapping[k] is not None
    }

output from mypy:

/tmp/mypytest.py:8: error: Key expression in dictionary comprehension has incompatible type "Optional[str]"; expected type "str"

if key_mapping.get(k) is None then it would fail the if-statement at the end of the dictionary comprehension and therefore get filtered out

if k is not in key_mapping then k is the result of the expression key_mapping.get(k,k). k can't be None because k comes from the keys of original_dict which has the type Dict[str, Any]

Versions: mypy 0.701, Python 3.7.4

no flags

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

Reproduce the report with the shown rename_keys dictionary comprehension using mypy 0.701 and Python 3.7.4. Trace how type refinements are handled for the if condition and indexed lookup, then verify that the incompatible Optional[str] diagnostic is resolved without allowing the None case through.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.