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

mypy doesn't narrow type upon assignment #9486

Closed
rhshadrach opened this issue Sep 25, 2020 · 2 comments
Closed

mypy doesn't narrow type upon assignment #9486

rhshadrach opened this issue Sep 25, 2020 · 2 comments
Labels
bug mypy got something wrong

Comments

@rhshadrach
Copy link

Example:

def foo():
    x: Union[str, Dict[str, str]] = {}
    x["a"] = "b"

mypy reports error: Unsupported target for indexed assignment ("Union[str, Dict[str, str]]").

Should mypy be able to narrow the type here to realize the assignment is okay? While the function may seem odd, this occurs when you have a long alias where the outer type is a union, e.g.:

AggFuncType = Union[
    AggFuncTypeBase,
    List[AggFuncTypeBase],
    Dict[Label, Union[AggFuncTypeBase, List[AggFuncTypeBase]]],
]

To solve, one can either add an assert/cast or also alias the inner type. But I was surprised mypy didn't do it automatically, so I thought I'd ask.

@rhshadrach rhshadrach added the bug mypy got something wrong label Sep 25, 2020
@hauntsaninja
Copy link
Collaborator

mypy will accept:

def foo() -> None:
    x: Union[str, Dict[str, str]]
    x = {}
    x["a"] = "b"

I agree that there being a difference here is surprising. There are a couple issues open about it, as well as a long recent thread in typing-sig.

@gvanrossum
Copy link
Member

So let's call this a duplicate of #2008. I think we should bite the bullet and change mypy so that there's no difference between the two.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

3 participants