来自Pylint的Cell-var-from-loop警告 [英] Cell-var-from-loop warning from Pylint

查看:159
本文介绍了来自Pylint的Cell-var-from-loop警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于以下代码:

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

Pylint报告了一个错误:

Pylint reported an error:


在循环中定义的单元变量sort_key(cell-var-from-loop)

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

有人可以提示这是怎么回事吗?从pylint源代码开始,描述为:

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?

推荐答案

名称 sort_key 实际调用该函数时,将在 lambda 正文中查找,因此它将看到值 sort_key 最近。由于您要立即调用 sort ,因此 sort_key 的值在使用结果函数对象之前不会改变,因此您可以放心地忽略该警告。要使其静音,可以将 sort_key 设置为 lambda 的参数的默认值:

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

这篇关于来自Pylint的Cell-var-from-loop警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆