python / mypy

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

False positive on return type #17445

Closed alexei closed 6 days ago

alexei commented 6 days ago

I found an instance where mypy is not behaving the way a developer would expect:

import random

def f1() -> int:
    if bool(random.getrandbits(1)):
        retval = 1
    return retval

def f2() -> int:
    if False:
        retval = 1
    return retval

mypy reports on line 13: "error: Cannot determine type of "retval" [has-type]", but not on line 7 as well. I would expect it to treat retval as an undefined variable as the condition can also be false - there's no way to tell.

Gist URL: https://gist.github.com/mypy-play/33d1f016c63e3c72dcaf1e89256b4af0 Playground URL: https://mypy-play.net/?mypy=latest&python=3.12&gist=33d1f016c63e3c72dcaf1e89256b4af0

hauntsaninja commented 6 days ago

You can enable the possibly-undefined error code https://mypy.readthedocs.io/en/stable/error_code_list2.html#warn-about-variables-that-are-defined-only-in-some-execution-paths-possibly-undefined

alexei commented 4 days ago

Thank you, @hauntsaninja