python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
18.52k stars 2.83k forks source link

Spurious assignment error in disjunt condition branches #17688

Open ZeeD opened 3 months ago

ZeeD commented 3 months ago

Playground url: https://mypy-play.net/?mypy=latest&python=3.12&flags=strict%2Cwarn-unused-configs&gist=d2e9766efcc27a2bc27d7226c0f6b444

def cond1() -> bool:
    return True

def cond2() -> bool:
    return True

def foo() -> None:
    if cond1():
        a = ''
        return

    if cond2():
        a = 123
        return

    a = False
    return

in this scenario, while a is a local variable the lifetime of it is determined by the if and return so there is no overlap between the case when a is a str and when is an int or a bool - those are "effectively" different variables.

Expected Behavior

no error triggered by mypy

Actual Behavior

main.py:13: error: Incompatible types in assignment (expression has type "int", variable has type "str")  [assignment]
main.py:16: error: Incompatible types in assignment (expression has type "bool", variable has type "str")  [assignment]
Found 2 errors in 1 file (checked 1 source file)
DetachHead commented 2 months ago

duplicate of #6232?

ZeeD commented 2 months ago

it's a bit of a "extended variant" (the concrete usecase is a bit different as is with if / else branches vs early return) but the gist is the same, yep