PY-COMP0002 · manual_set_comprehension
Count fresh sets populated by a loop that can be one set comprehension.
This is a deterministic rule for python. Read its implementation.
Definition
Section titled “Definition”Detect a local name initialized by the unshadowed builtin set() immediately before a
synchronous for loop. Require the loop’s only effect to be name.add(expression), optionally
inside one if without an else. Convert that condition directly into the comprehension
filter. The result is the number of proven candidates. A safe UTF-8 edit replaces the
initialization and loop when every required expression is available as single-line source.
Evidence
Section titled “Evidence”Each finding identifies the fresh set, initialization-to-loop range, and loop line. The safe fix preserves a plain or annotated assignment and retains the iterable, target, expression, and optional condition in their original evaluation order. The value is the number of loops a set comprehension would replace exactly.
Exceptions
Section titled “Exceptions”Abstain when set is shadowed, the loop is asynchronous, the set already contains values, the
body has multiple effects, an else or control-flow statement exists, or the expression reads
the set being built. Also abstain inside exception handlers, in module or class scope, when a
a loop binding is referenced elsewhere in its function, or when assignment expressions,
await, or yield make scope and evaluation semantics differ. Attribute-only targets and
dynamic local-scope introspection also suppress the finding. Comments suppress the automatic
edit rather than being deleted.
Examples
Section titled “Examples”Bad
`values = set(); for item in source: values.add(normalize(item))` manually builds a set.A body containing only `if item.valid: values.add(item.key)` is the filtered form.
Goodvalues = {normalize(item) for item in source} and
values = {item.key for item in source if item.valid} state the collection directly. A loop
with logging, an else, an async iterator, or later use of item remains explicit.
References
Section titled “References”- Cites “The Python Tutorial”, Sets and set comprehensions. Open reference
- Cites “The Python Language Reference”, Displays for lists, sets and dictionaries. Open reference
- Cites “Fluent Python”, chapter 2, An Array of Sequences