This rule raises an issue when several elements are added to the same set through consecutive add() calls.

Why is this an issue?

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})

What is the potential impact?

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.

Exceptions

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.

How to fix it

Group the added elements into a single update() call, passing them as a set literal.

Code examples

Noncompliant code example

def collect_tags(base_tags, name):
    tags = set(base_tags)
    tags.add("archived")  # Noncompliant
    tags.add("verified")
    tags.add(name)
    return tags

Compliant solution

def collect_tags(base_tags, name):
    tags = set(base_tags)
    tags.update({"archived", "verified", name})
    return tags

How does this work?

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.

Pitfalls

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.

Resources

Documentation

Related rules