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?

share|improve this question
    
What kind of object is results? Ordinary list? Something else? – Kevin Aug 14 '14 at 17:59
    
See e.g. stackoverflow.com/q/12423614/3001761 – jonrsharpe Aug 14 '14 at 18:00
    
@Kevin e.g. results = [{key: value}, {key: value} ...] – xis Aug 14 '14 at 18:14
    
Ok. In that case, I agree with chepner that you don't need to worry about the warning here. – Kevin Aug 14 '14 at 18:19
up vote 38 down vote accepted

The name sort_key in the body of the lambda will be looked up when the function is actually called, so it will see what ever 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))
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.