This rule raises an issue when several elements are added to the same set through consecutive add() calls.
Adding elements to a set one statement at a time is unnecessary when the update() method exists:
my_set.add(first) my_set.add(second) my_set.add(third)
The update() method combines all additions into a single call and avoids the overhead of repeated add() invocations:
my_set.update({first, second, third})
Grouping the additions makes the intent explicit: the reader sees one operation that grows the set instead of a series of independent statements. It also removes redundant call overhead, since the attribute lookup and the method call are resolved once instead of once per element.
No issue is raised when fewer than three consecutive calls target the set, or when other statements are interleaved between the add()
calls:
my_set.add(first)
log.debug("first added")
my_set.add(second)
my_set.add(third)
No issue is raised either when an added element reads the set, such as my_set.add(len(my_set)), because grouping the calls would
change the result.
Group the added elements into a single update() call, passing them as a set literal.
def collect_tags(base_tags, name):
tags = set(base_tags)
tags.add("archived") # Noncompliant
tags.add("verified")
tags.add(name)
return tags
def collect_tags(base_tags, name):
tags = set(base_tags)
tags.update({"archived", "verified", name})
return tags
update() iterates over its argument and adds every element to the set, so the result is exactly the same as the individual calls. The
augmented assignment my_set |= {first, second, third} is equivalent to update() with another set and can be used instead
when it is more readable.
Do not confuse update() with add(): my_set.add(other_collection) adds the collection itself as a single
element, and fails when that collection is not hashable, while update() adds its elements.
set.update() methodset,
frozenset