Cell-var-from-loop warning from Pylint

PythonLambdaClosures

Python Problem Overview


For the following code:

for sort_key, order in query_data['sort']:
    results.sort(key=lambda k: get_from_dot_path(k, sort_key),
                 reverse=(order == -1))

Pylint reported an error:

> Cell variable sort_key defined in loop (cell-var-from-loop)

Could anyone give a hint what is happening here? From pylint source code the description is:

> 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.

But I do not have a clue what it means. Could anyone give an example of the problem?

Python Solutions


Solution 1 - Python

The name sort_key in the body of the lambda will be looked up when the function is actually called, so it will see the value sort_key had most recently. Since you are calling sort immediately, the value of sort_key will not change before the resulting function object is used, so you can safely ignore the warning. To silence it, you can make sort_key the default value of a parameter to the lambda:

results.sort(key=lambda k, sk=sort_key: get_from_dot_path(k, sk),
             reverse=(order == -1))

Solution 2 - Python

Use functools.partial():

import functools
results.sort(key=functools.partial(get_from_dot_path, foo=sort_key),
             reverse=(order == -1))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionxisView Question on Stackoverflow
Solution 1 - PythonchepnerView Answer on Stackoverflow
Solution 2 - PythonmejdevView Answer on Stackoverflow