contribute checking for "miscaptured" variables in loops

未关闭
#177 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

评估

难度
4/5
预计耗时
3-5 天
新手友好度
35/100
Issue 类型
功能
描述清晰度
基本清楚
活跃度
停滞
技术栈
python
领域
tooling

调研方向

先阅读链接的 check-miscaptures.py 脚本及其示例输出,以了解它针对 lambda、命名函数、循环和推导式生成的警告。然后检查 pyflakes,找出现有的源代码检查入口;当 pyflakes 报告相同的可疑捕获,但不报告所示的默认参数形式时,即视为完成。

由索引模型根据 Issue 内容生成。

描述

Original report by daira (@daira?) on Launchpad:


Tahoe-LAFS, a large Python codebase implementing a distributed filesystem, uses a script called "check-miscaptures" ( https://tahoe-lafs.org/trac/tahoe-lafs/browser/trunk/misc/coding_tools/check-miscaptures.py) to catch a class of errors resulting in unexpected behaviour when capturing variables in loops.

An example of incorrect code that it would catch is:

  a = [None]*10
  for i in range(0, 10):
       a[i] = lambda x: x+i

  # The programmer expected a[x](y) to be equivalent to x+y


  print a[2](2)  # not 4, but 11

This happens because all of the a[i] capture the same mutable variable i, which is 9 after the loop when the lambda is called.

For this example, the output of check-miscaptures is:

Checking miscapture.py...
miscapture.py:3 captures 'i' assigned at line 2
1 suspiciously captured variables in 1 out of 1 file(s).

Changing the loop body to "a[i] = lambda x, i=i: x+i" fixes the problem, and check-miscaptures will not report a warning for the fixed code (it rarely gives false positives, and when it does they are easy to suppress).

The same problem can happen with named functions rather than lambdas, and with other kinds of loop or list comprehensions. More realistic examples are common in programs that define lots of callback functions, for example when using asynchronous libraries such as Twisted.

This ticket is to integrate the checking done by this script into pyflakes.

主要语言
Python
星标
1.5k
派生
207
平均合并
4 分钟
30 天内合并 PR
1

环境准备

这个项目没有提供开发容器、Dockerfile 或贡献指南,环境需要你自己搭建:先看它的 README,通用步骤见我们的新手贡献指南。

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

PyCQA/pyflakes 的其他 Issue

查看 PyCQA/pyflakes 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。