跳到内容

unnecessary-comprehension (C416)(不必要的推导式)

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

修复总是可用的。

作用

检查不必要的字典、列表和集合推导式。

为什么这不好?

如果元素未更改,则使用字典/列表/集合推导式来构建数据结构是不必要的。请使用 dict()list()set() 包裹可迭代对象。

示例

{a: b for a, b in iterable}
[x for x in iterable]
{x for x in iterable}

建议改为

dict(iterable)
list(iterable)
set(iterable)

已知问题

对于迭代映射的字典推导式,此规则可能会产生误报。 dict 构造函数的行为取决于它接收的是序列(例如,列表)还是映射(例如,字典)。当推导式迭代映射的键时,将其替换为 dict() 构造函数调用会产生不同的结果。

例如

>>> d1 = {(1, 2): 3, (4, 5): 6}
>>> {x: y for x, y in d1}  # Iterates over the keys of a mapping
{1: 2, 4: 5}
>>> dict(d1)               # Ruff's incorrect suggested fix
(1, 2): 3, (4, 5): 6}
>>> dict(d1.keys())        # Correct fix
{1: 2, 4: 5}

当推导式迭代序列时,Ruff 建议的修复是正确的。但是,Ruff 无法始终如一地推断可迭代对象的类型是序列还是映射,也无法为映射建议正确的修复。

修复安全性

由于字典推导式存在已知问题,因此此修复被标记为不安全。

此外,此修复可能会在重写推导式时删除注释。