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 incorrectly tracks attribute type in chained ifs with assignment #6810

Open
serhiy-storchaka opened this issue May 10, 2019 · 3 comments
Labels
bug mypy got something wrong false-positive mypy gave an error on correct code priority-1-normal

Comments

@serhiy-storchaka
Copy link
Member

$ cat b.py 
from typing import Optional

class A:
    x: Optional[str]

def f(a: A) -> None:
    if not a.x:
        pass
    elif a.x == "x":
        a = A()
    else:
        y: str = a.x

$ mypy b.py 
b.py:12: error: Incompatible types in assignment (expression has type "Optional[str]", variable has type "str")

$ mypy --version
mypy 0.701

The assignment a = A() should not affect the code in the else branch.

@ilevkivskyi ilevkivskyi added bug mypy got something wrong false-positive mypy gave an error on correct code priority-1-normal labels May 10, 2019
@ilevkivskyi
Copy link
Member

Thanks for reporting! This looks like a bug in conditional type binder. There is one similar issue #5378.

@pmav99
Copy link

pmav99 commented Jun 6, 2019

A simpler demonstration of the bug:

import typing

def to_int(text: str) -> typing.Union[int, str]:
    """ Cast to integer if value is numeric or return unchanged """
    if text.isnumeric():
        result = int(text)
    else:
        result = text
    return result
$ mypy asdf.py
asdf.py:8: error: Incompatible types in assignment (expression has type "str", variable has type "int")

Tried this in versions:

  • 0.701
  • 0.670
  • 0.590

@ilevkivskyi
Copy link
Member

@pmav99 this is totally unrelated, mypy doesn't infer unions from conditional definitions, there is a separate issue about this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong false-positive mypy gave an error on correct code priority-1-normal
Projects
None yet
Development

No branches or pull requests

3 participants