pylint-dev / pylint

It's not just a linter that annoys you!
https://pylint.readthedocs.io/en/latest/
GNU General Public License v2.0
5.33k stars 1.14k forks source link

`possibly-used-before-assigment` fails to understand test with immutable `bool` #10095

Closed lucascolley closed 2 days ago

lucascolley commented 2 days ago

Bug description

As per the docs, this works:

def func(x: bool) -> None:
    if not x:
        msg = 'hello world'
    print("hi")
    if not x:
        print(msg)
    return

but only because we are using the same test, not x, twice.

If we instead use the test x, pylint fails:

def func(x: bool) -> None:
    if not x:
        msg = 'hello world'
    print("hi")
    if x:
        return
    print(msg)

Command used

pylint

Pylint output

E0606: Possibly using variable 'msg' before assignment (possibly-used-before-assignment)

Expected behavior

It is impossible for print("hi") (or any intervening code that doesn't assign to x) to change the value of x since it is an immutable bool. If not x is False at the top of the function, x will always be True at the bottom of the function. So it is impossible for msg to be used before assignment - this is a false positive.

Pylint version

pylint 3.3.1
jacobtylerwalls commented 2 days ago

Thanks for the report, this is an even simpler case than the one discussed in #9662, for which I would expect any fix to also cover this case. 👍

jacobtylerwalls commented 2 days ago

So it is impossible for msg to be used before assignment - this is a false positive.

Part of the premise that I want to make explicit here is that there are no other reassignments to x in the middle of the function. x = not x before the second test at the bottom of the function would violate your example.