Immutable Sets With frozenset
Concepts covered: Frozensets
Pipelines keep reference collections that many functions read and none should change: the event types a validator accepts, the country codes a report covers, the columns a schema requires. In an ordinary set, any function that calls .add() on such a collection changes it, and every other reader inherits the change. A frozenset is a set whose membership is fixed at construction. The frozenset() constructor takes any iterable and deduplicates it the way set() does. There is no literal syntax, so frozenset() with no argument is also the only way to write an empty one.
VALID_EVENTS = frozenset(["view", "add_to_cart", "checkout", "refund", "view"])
REVENUE_EVENTS = {"checkout", "refund"}
print(len(VALID_EVENTS))
print("checkout" in VALID_EVENTS)
print(sorted(VALID_EVENTS - REVENUE_EVENTS))
print(type(VALID_EVENTS & REVENUE_EVENTS).__name__)
print(type(REVENUE_EVENTS & VALID_EVENTS).__name__)
print(REVENUE_EVENTS <= VALID_EVENTS)
print(VALID_EVENTS == set(VALID_EVENTS))
try:
VALID_EVENTS.add("signup")
except AttributeError as err:
print("AttributeError:", err)Output:
4 True ['add_to_cart', 'view'] frozenset set True True AttributeError: 'frozenset' object has no attribute 'add'
Everything that reads a set still works on the frozen one: len, in, iteration, the subset comparisons and all 4 operators. The - and & lines build new objects and leave VALID_EVENTS as it was. Each result takes the type of its left operand, so frozenset & set gives a frozenset and set & frozenset gives a set. Equality compares elements only, which is why a frozenset equals the set built from it. The last line fails with AttributeError because the type has no add method at all: the mutating methods were never defined on it.
| Operation | On a set | On a frozenset |
|---|---|---|
| add, remove, discard, pop, clear | Changes the set in place | AttributeError |
| update, intersection_update, difference_update, symmetric_difference_update | Changes the set in place | AttributeError |
| union, intersection, difference, symmetric_difference (methods and operators) | New set | New frozenset |
| in, len, iteration, subset comparisons, ==, isdisjoint() | Works | Works |
| hash() | TypeError: unhashable type: 'set' | An int computed from the elements |
The last row is the reason the type exists. A hash table files each key under a number computed from its contents. If those contents changed after filing, the key would sit under a stale number where no lookup could reach it, so Python refuses to hash a mutable set at all. A frozenset's contents cannot change, so its hash is computed once from its elements and cached. Frozensets holding the same elements hash equally, whatever order they were built in.
Immutability makes 2 other things cheap. frozenset.copy() and frozenset(fs) return the same object, because a copy of something unchangeable could never differ from the original. A frozenset is also a safe default argument. def validate(event, allowed=frozenset({"view", "checkout"})) creates the default once and shares it across every call. That sharing is harmless when no call can modify the default, and it is the classic shared-default bug when the default is a set.
Augmented assignment on a frozenset
The table lists no way to update a frozenset, yet allowed |= {"refund"} runs without error. frozenset defines no in-place __ior__ method, so Python falls back to allowed = allowed | {"refund"}. It builds a new frozenset and rebinds the name. Any other name that still points at the original object sees the original contents.
allowed = frozenset({"view", "checkout"})
shared = allowed
allowed |= {"refund"}
print(sorted(allowed))
print(sorted(shared))
print(allowed is shared)Output:
['checkout', 'refund', 'view'] ['checkout', 'view'] False
The same fallback applies to &=, -= and ^=. It happens only when the left operand lacks the in-place method. The question below changes 1 thing: the first line builds a plain set.
The same 6 lines run with the first line changed to allowed = {"view", "checkout"}, a plain set. What does print(sorted(shared)) print?
- ['checkout', 'refund', 'view']
- ['checkout', 'view']
- A TypeError, because |= needs both operands to be the same type
- ['refund']
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.