W0640 cell-var-from-loop

Message

'Cell variable %s defined in loop'

Description

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.

Example

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 = [
    func(1)
    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.