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.31k stars 1.13k forks source link

False positive ``cell-var-from-loop`` when there is only one element in an iterator #1934

Open cdyson37 opened 6 years ago

cdyson37 commented 6 years ago

I think this is a spurious warning. In the below, s is not defined in any loop.

Steps to reproduce

# pylint: disable=invalid-name,missing-docstring

for z in [0]:
    s = set()

    def f():
        for x in [0]:
            s.add(x)

    f()
No config file found, using default configuration
************* Module bug
W:  7,12: Cell variable s defined in loop (cell-var-from-loop)

Current behavior

Triggers cell-var-from-loop

Expected behavior

No warning

pylint --version output

$ pylint --version
No config file found, using default configuration
pylint 1.8.2, 
astroid 1.6.1
Python 2.7.14 (default, Sep 16 2017, 17:49:51) 
[GCC 7.3.0]
PCManticore commented 6 years ago

While I admit that this looks like a bug in pylint, I wonder though why the s is not initialised in the body of the function, which can then return it?

cdyson37 commented 6 years ago

This is very much reduced down for a real world (non-insane, honest) example :)

PCManticore commented 6 years ago

Gotcha, I was just curious. :)

cdyson37 commented 6 years ago

The original code iterates up and down a tree visiting things and accumulating what it sees. I could tell you more but I'd have to kill you ;)

SamyCookie commented 5 years ago

Does https://github.com/PyCQA/pylint/pull/2276 fixed this issue ?

PCManticore commented 5 years ago

@SamyCookie Doesn't seem to be.

SamyCookie commented 3 years ago

another (fictive) example that just regressed since 2.10 version, I also got a spurious cell-var-from-loop warning:

for n in range(10):
    plus_n = lambda i: i + n
    foo = plus_n(42) + plus_n(17)
    print(foo)