Skip to content

Type refinements are not applied to index expressions #7339

Open
@tomalexander

Description

@tomalexander

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions