pylint icon indicating copy to clipboard operation
pylint copied to clipboard

False positive `used-before-assignment`

Open SpecLad opened this issue 10 months ago • 5 comments

Bug description

# pylint: disable=missing-docstring

def foobar(x):
    if x not in ["A"]:
        v = []

    if x == "B":
        print(v)
    elif x == "A":
        v = []
    else:
        raise RuntimeError(f'{x}')

Configuration


Command used

pylint pylint_repro.py

Pylint output

************* Module pylint_repro
pylint_repro.py:8:14: E0601: Using variable 'v' before assignment (used-before-assignment)

------------------------------------------------------------------
Your code has been rated at 3.75/10 (previous run: 0.00/10, +3.75)

Expected behavior

Preferably no errors at all, but failing that, the error should be possibly-used-before-assignment, not used-before-assignment.

Pylint version

pylint 3.3.3
astroid 3.3.8
Python 3.12.3 (main, Nov  6 2024, 18:32:19) [GCC 13.2.0]

OS / Environment

Ubuntu 24.04.

Additional dependencies


SpecLad avatar Jan 20 '25 10:01 SpecLad

I also experienced this issue with the following settings:

pylint 3.3.6
astroid 3.3.9
Python 3.12.10

and

pylint 3.2.7
astroid 3.2.4
Python 3.12.10

When I downgraded to pylint 3.1.1 the error no longer occurred.

mkavulich avatar Apr 21 '25 18:04 mkavulich

> def foobar(x):
>     if x not in ["A"]:
>         v = []
> 
>     if x == "B":
>         print(v)
>     elif x == "A":
>         v = []
>     else:
>         raise RuntimeError(f'{x}')

I don't get it. Isn't the linter warning correct in your case? Assignment is not guaranteed, isn't it?

buhtz avatar Jun 10 '25 09:06 buhtz

I don't get it. Isn't the linter warning correct in your case? Assignment is not guaranteed, isn't it?

used-before-assignment should only be emitted if a variable is definitely unassigned, which is not the case here.

SpecLad avatar Jun 10 '25 10:06 SpecLad

Interestingly, bisect shows that this was introduced by commit 67bfab41b6a830cbab669b4eb15204690c64846d, which added the possibly-used-before-assignment warning.

SpecLad avatar Jun 10 '25 10:06 SpecLad

An even simpler reproducer:

# pylint: disable=missing-docstring

def foobar(x):
    if x != 0:
        v = None

    if x == 1:
        print(v)
    else:
        v = None

SpecLad avatar Jun 10 '25 10:06 SpecLad