跳到内容

unnecessary-generator-set (C401) (不必要的生成器集合 (C401))

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

修复总是可用的。

作用

Checks for unnecessary generators that can be rewritten as set comprehensions (or with set() directly). (检查可以重写为集合推导式(或直接使用set())的不必要的生成器。)

为什么这不好?

It is unnecessary to use set around a generator expression, since there are equivalent comprehensions for these types. Using a comprehension is clearer and more idiomatic. (围绕生成器表达式使用set是不必要的,因为对于这些类型存在等效的推导式。使用推导式更清晰也更符合语言习惯。)

Further, if the comprehension can be removed entirely, as in the case of set(x for x in foo), it's better to use set(foo) directly, since it's even more direct. (此外,如果可以完全删除推导式,例如在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. (此规则的修复被标记为不安全,因为它在重写调用时有时会删除注释。但在大多数情况下,注释将被保留。)