Skip to content
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

Dict values not inferred correctly #6088

Closed
mehdigmira opened this issue Dec 19, 2018 · 4 comments
Closed

Dict values not inferred correctly #6088

mehdigmira opened this issue Dec 19, 2018 · 4 comments

Comments

@mehdigmira
Copy link

In this code:

from typing import Dict, Optional


def f (x: Optional[int]):
    if x is not None:
        x += 1

mypy is smart enough to understand to infer that x is of type int in the last line. However is this example:

from typing import Dict, Optional

d = {"k": 1}  # type: Dict[str, Optional[int]]

if d.get("k") is not None:
    d["k"] += 1

mypy is not able to infer that d["k"] is an int. We've been using mypy for the few months and this is really painful, since it's a very common programming pattern.

@ilevkivskyi
Copy link
Member

This however works perfectly:

if d["k"] is not None:
    d["k"] += 1

since it's a very common programming pattern

I don't think I have ever seen this. (And we have several million lines of Python code.) Have you tried collections.defaultdict?

In any case this is very low priority, since it is already unsafe, and using type binder on function calls feels even worse. Maybe we should just close this?

@JukkaL
Copy link
Collaborator

JukkaL commented Dec 19, 2018

Special casing dict.get seems conceptually not terrible, at least if this idiom turns out to be more common than we think now. But I agree that we don't have enough evidence to say that this is a widespread idiom.

This can be worked around using a cast, but then the assignment in the example needs to be written as d["k"] = cast(int, d["k"]) + 1 which is pretty verbose.

@mehdigmira
Copy link
Author

This doesn't work either:

from typing import Dict, Optional

d = {"k": 1}  # type: Dict[str, Optional[int]]

k = "k"
if d[k] is not None:
    d[k] += 1

@msullivan
Copy link
Collaborator

I don't think we're going to support this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants