Pylint: False positive for cell-var-from-loop

Created on 16 Sep 2019  路  4Comments  路  Source: PyCQA/pylint

Steps to reproduce

for i in [[2], [3]]:
    next(filter(lambda j, ix=i[0]: j == ix, [1, 3]))

Current behavior

W0640: Cell variable i defined in loop (cell-var-from-loop)

Expected behavior

I would expect to avoid the warning because the "i" is passed as default argument to the lambda. I get the false positive also if I loop along objects instead of list.
But I don't get it for the code below (looping along ints)

for i in [2, 3]:
    next(filter(lambda j, ix=i: j == ix, [1, 3]))

pylint --version output

pylint 2.3.1
astroid 2.2.5
Python 3.7.4 (v3.7.4:e09359112e, Jul 8 2019, 14:54:52)

thanks

bug checkers

Most helpful comment

same issue for me, here a functional reduced test case:

handlers = []
for i in range(10):
    handlers.append(lambda: i)

This isn't a _false_ positive, since i is only resolved when the handlers are called:

In [1]: handlers = []

In [2]: for i in range(10):
   ...:     handlers.append(lambda: i)
   ...:

In [3]: [h() for h in handlers]
Out[3]: [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]

Ouch, you're so right. My bad, bad example !

All 4 comments

Thanks for the report.

same issue for me, here a functional reduced test case:

handlers = []
for i in range(10):
    handlers.append(lambda: i)

same issue for me, here a functional reduced test case:

handlers = []
for i in range(10):
    handlers.append(lambda: i)

This isn't a _false_ positive, since i is only resolved when the handlers are called:

In [1]: handlers = []

In [2]: for i in range(10):
   ...:     handlers.append(lambda: i)
   ...:

In [3]: [h() for h in handlers]
Out[3]: [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]

same issue for me, here a functional reduced test case:

handlers = []
for i in range(10):
    handlers.append(lambda: i)

This isn't a _false_ positive, since i is only resolved when the handlers are called:

In [1]: handlers = []

In [2]: for i in range(10):
   ...:     handlers.append(lambda: i)
   ...:

In [3]: [h() for h in handlers]
Out[3]: [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]

Ouch, you're so right. My bad, bad example !

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ethanchewy picture ethanchewy  路  3Comments

PCManticore picture PCManticore  路  3Comments

Hubro picture Hubro  路  3Comments

TBoshoven picture TBoshoven  路  3Comments

glmdgrielson picture glmdgrielson  路  3Comments