W0640 cell-var-from-loop


'Cell variable %s defined in loop'


A variable used in a closure is defined in a loop. This will result in all closures using the same value for the closed-over variable.


When using a loop variable (elem) in a closure (the lambda defined in the comprehension), the value of that variable will be the same every time (the last value the variable had before the closed function/lambda is called).

funcs = [
    lambda x: x + elem
    for elem in range(3)
results = [
    for func in funcs
# results == [3, 3, 3]
2:18: W0640: Cell variable elem defined in loop

Running Pylint locally? In your CI?

There is a better way! Run PyCodeQual & get Pylint findings with history, diffs and statistics.

Click here to find out more.