跳到内容

unnecessary-generator-set (C401)

添加于 v0.0.61 · 相关问题 · 查看源码

Derived from the flake8-comprehensions linter. (源自 flake8-comprehensions linter。)

修复总是可用的。

作用

检查不必要的生成器,并建议将其重写为集合推导式(或直接使用 set())。

为什么这不好?

在生成器表达式外使用 set 是不必要的,因为这些类型有对应的推导式。使用推导式更加清晰且符合惯用法。

此外,如果推导式可以完全省略(例如 set(x for x in foo)),最好直接使用 set(foo),因为它更加简洁直接。

示例

set(f(x) for x in foo)
set(x for x in foo)
set((x for x in foo))

建议改为

{f(x) for x in foo}
set(foo)
set(foo)

修复安全性

This rule's fix is marked as unsafe, as it may occasionally drop comments when rewriting the call. In most cases, though, comments will be preserved. (此规则的修复被标记为不安全,因为它在重写调用时有时会删除注释。但在大多数情况下,注释将被保留。)