-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Open
Labels
false-positivemypy gave an error on correct codemypy gave an error on correct codefeaturepriority-1-normaltopic-type-narrowingConditional type narrowing / binderConditional type narrowing / binder
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
mathieui, deniscostadsc, fpdotmonkey, rnestler, lafrech and 1 more
Metadata
Metadata
Assignees
Labels
false-positivemypy gave an error on correct codemypy gave an error on correct codefeaturepriority-1-normaltopic-type-narrowingConditional type narrowing / binderConditional type narrowing / binder