Advanced Set Pitfalls

Concepts covered: Dunder Methods, Sets

The set bugs that reach production share a shape. The code runs, the output looks plausible, and the damage shows up later in a report or a rerun. Most of them come from the 5 patterns below.

Changing a set while looping over it

A set iterator records the set's size when it starts and checks it on every step. Removing or adding an element inside the loop changes the size, and the next step raises RuntimeError: Set changed size during iteration. Pairing 1 add with 1 remove keeps the size constant and silences the check. That is worse, because elements can then be skipped or visited twice with no error at all. Every fix takes the iteration off the live set: loop over a snapshot with for x in list(s), build a new set with a comprehension, or apply the whole change at once with s -= expired.

list(active) copies the 5 ids before the loop starts, so the removals change a set the loop is no longer reading. For a bulk removal like this one, active -= expired does the whole job in 1 call costing O(len(expired)).

Sets where lists belong, and set order

A set answers "which distinct values occurred". Code that needs to know how many, or in what sequence, loses that information as soon as it builds a set. Summing a set of payment amounts drops every repeated amount, and a set of pipeline steps forgets which step ran first. Iteration order looks dependable because small ints hash to themselves and often print sorted, until one of them wraps around the table.

payments = [1999, 500, 1999, 4250]
print(sum(payments), sum(set(payments)))
print({1, 8})
steps = ["extract", "validate", "extract", "load"]
print(sorted(set(steps)))
print(list(dict.fromkeys(steps)))

Output:

8748 6749
{8, 1}
['extract', 'load', 'validate']
['extract', 'validate', 'load']

The 2 payments of 1999 cents collapsed into a single element, so revenue came out 1999 cents short. {1, 8} prints as {8, 1} because 8 lands in slot 0 of an 8-slot table, ahead of 1 in slot 1. String order is less predictable still. String hashes are randomised per process through PYTHONHASHSEED, so a set of column names can serialise in a different order on every run and churn every diff and checksum downstream. Where order is visible, sorted(s) fixes it alphabetically, and dict.fromkeys(items) deduplicates while keeping the order in which items were first seen.

Empty braces and the set() argument

Braces default to dict: {} is an empty dict, and only a non-empty brace literal without colons is a set. seen = {} survives if x in seen, which works on dicts, and fails later at seen.add(x) with AttributeError: 'dict' object has no attribute 'add'. The constructor has the opposite trap. set() takes 1 iterable and iterates over it, so set("checkout") holds letters.

ExpressionResult
{}Empty dict
set()Empty set
frozenset()Empty frozenset
{"checkout"}Set with 1 string
set("checkout")Set of 7 characters
set(["checkout"])Set with 1 string

Custom objects in sets

A class without __eq__ and __hash__ compares by identity. Then 2 Customer objects for the same email count as 2 elements, and deduplication silently does nothing. Defining __eq__ alone sets __hash__ to None, so adding an instance to a set raises TypeError: unhashable type: 'Customer'. Defining both on a field that can change is the dangerous case.

class Customer:
    def __init__(self, email):
        self.email = email

    def __eq__(self, other):
        return self.email == other.email

    def __hash__(self):
        return hash(self.email)


c = Customer("ana@shop.io")
customers = {c}
c.email = "ana@newshop.io"
print(len(customers))
print(c in customers)
print(Customer("ana@shop.io") in customers)

Output:

1
False
False

The set filed c under the hash of its old email. After the change, a lookup for c computes the new hash and finds nothing filed under it. A lookup for the old email finds the right slot but fails __eq__. The object is still inside the set and counted by len, yet membership tests cannot reach it. Hash only fields that never change after construction, such as a database id, or store an immutable value like a tuple in the set in place of the object. @dataclass(frozen=True) generates a matching __eq__ and __hash__ and blocks attribute assignment.

Do
  • Freeze a set with frozenset() before using it as a dict key or set element
  • Hold reference collections that must not change as module-level frozensets
  • Build a set once, outside the loop, and test membership against it inside
  • Iterate over list(s) when the loop body adds to or removes from s
  • Use sorted(s) or dict.fromkeys() wherever output order is visible
Avoid
  • Sum, count or average values after putting them in a set
  • Write {} for an empty set, because it creates an empty dict
  • Call set() inside a loop condition, which rebuilds the set on every pass
  • Hash a custom object on a field that can change after it enters a set
  • Rely on set iteration order, even when small ints happen to print sorted

About this lesson

This section is part of the Sets: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.