-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Type refinements are not applied to index expressions #7339
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Your example doesn't type check because mypy never applies any type restrictions to function calls (even for builtin ones where the semantics is known to be pure), and this is unlikely to change. But when I tried to propose refactoring it to use only index expressions instead of function call, it looks like there is indeed an issue, for example this fails as well: x: List[Optional[str]]
y: Dict[str, int] = {x[i]: 0 for i in range(5) if x[i]} It looks like the cause is that binder only considers things like cc @JukkaL |
Narrowing down expressions like |
OK, this makes sense. |
#2458 has an interesting example of this with |
I think I'm hitting a similar issue with the following code: this_is_fine = {
"bar": True,
"value_0": 1.0,
"value_1": 2.0,
}
this_is_not = {
"bar": True,
**{f"value_{n}": float(n) for n in range(2)},
} While the first one compiles fine I get I created https://github.com/rnestler/minimal-example-for-mypy-dict-issue to reproduce the issue. |
In case it helps anyone brought here by their search engine, I stumbled upon the same case as OP today and solved it with a cast. 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 {
typing.cast(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
} |
Ran into this issue today, I believe mypy is incorrectly flagging this as an error:
output from mypy:
if
key_mapping.get(k)
isNone
then it would fail the if-statement at the end of the dictionary comprehension and therefore get filtered outif
k
is not inkey_mapping
thenk
is the result of the expressionkey_mapping.get(k,k)
.k
can't beNone
becausek
comes from the keys oforiginal_dict
which has the typeDict[str, Any]
Versions: mypy 0.701, Python 3.7.4
no flags
The text was updated successfully, but these errors were encountered: