Sub topic 11
frozenset: immutable sets
This chapter assumes you know how ordinary sets work: creating them, membership tests, and the union, intersection and difference operators. It also assumes you know the difference between mutable and immutable objects, and that dictionary keys must be hashable. Here you will learn what frozenset adds, how it behaves, and when to choose it over set.
Why a second set type exists
A set is mutable. You can add and remove elements, so its contents can change after it is created. Python does not let a mutable container with value-based equality be hashable, because its hash would change when its contents change. That would break any dict or set that stored it.
The result is a restriction you may have already met: a set cannot be a dictionary key and cannot be an element of another set.
try:
nested = {{1, 2}, {3, 4}}
except TypeError as e:
print(e) # unhashable type: 'set'
try:
d = {{1, 2}: "pair"}
except TypeError as e:
print(e) # unhashable type: 'set'A frozenset solves this. It holds unique elements like a set, but it cannot change after creation. Because its contents are fixed, Python can compute a stable hash for it. That makes a frozenset usable wherever a hashable value is required.
Creating a frozenset
There is no literal syntax for a frozenset. You always build one by calling frozenset() with any iterable, or with no argument for an empty one.
from_list = frozenset([3, 1, 2, 3])
from_string = frozenset("hello")
empty = frozenset()
print(len(from_list)) # 3, duplicates are dropped
print(len(from_string)) # 4, because 'l' appears twice
print(len(empty)) # 0Unlike the empty set, there is no ambiguity with {} here. The call frozenset() is always the way to write an empty frozenset.
The elements must still be hashable, for the same reason as in a regular set. A frozenset of lists fails, but a frozenset of tuples or of other frozensets works.
ok = frozenset([(1, 2), (3, 4)])
print((1, 2) in ok) # True
try:
bad = frozenset([[1, 2], [3, 4]])
except TypeError as e:
print(e) # unhashable type: 'list'What a frozenset can and cannot do
A frozenset supports every operation that only reads. It does not have any method that changes its contents.
| Operation | set | frozenset | Column |
|---|---|---|---|
| `in`, `len()`, iteration | yes | yes | |
| `\ | `, `&`, `-`, `^` and the matching methods | yes | yes, returns a new frozenset |
| `<`, `<=`, `>`, `>=`, `isdisjoint()` | yes | yes | |
| `copy()` | yes | yes | |
| `add()`, `remove()`, `discard()`, `pop()`, `clear()` | yes | no | |
| `update()`, `\ | =`, `&=` and other in-place forms | yes | no (the operator rebinds the name instead) |
| Hashable | no | yes |
Trying to call a mutating method raises AttributeError, because the method does not exist on the type.
fs = frozenset([1, 2, 3])
print(2 in fs) # True
print(len(fs)) # 3
try:
fs.add(4)
except AttributeError:
print("frozenset has no add method")Set algebra with frozensets
The binary operators and methods work on frozensets and always produce a new frozenset. The original is never changed.
a = frozenset({1, 2, 3, 4})
b = frozenset({3, 4, 5})
print(sorted(a | b)) # [1, 2, 3, 4, 5]
print(sorted(a & b)) # [3, 4]
print(sorted(a - b)) # [1, 2]
print(sorted(a ^ b)) # [1, 2, 5]
print(type(a | b)) # <class 'frozenset'>The type of the result when you mix set and frozenset
When the two operands have different types, the result takes the type of the left operand. This detail surprises people because the operators look symmetric.
s = {1, 2}
f = frozenset({2, 3})
print(type(s | f)) # <class 'set'>
print(type(f | s)) # <class 'frozenset'>
print(s | f == f | s) # True, the elements are equalEquality between a set and a frozenset compares only the elements. The types do not matter, so {1, 2} == frozenset({1, 2}) is True.
Augmented assignment does not mutate
The expression fs |= {5} looks like an in-place update. A frozenset has no __ior__ method, so Python falls back to fs = fs | {5}. This builds a new frozenset and rebinds the name. Any other variable that still refers to the old object keeps the old contents.
fs = frozenset({1, 2})
alias = fs
fs |= {3}
print(sorted(fs)) # [1, 2, 3]
print(sorted(alias)) # [1, 2]
print(fs is alias) # FalseA regular set behaves differently here. With s |= {3}, both names would see the change, because the same object is modified.
Using frozensets as dict keys and set elements
The main reason to use a frozenset is that it can be a dictionary key. Two frozensets with the same elements are equal and have the same hash, regardless of the order in which you listed the elements.
fs = frozenset([1, 2, 3])
lookup = {fs: "numbers"}
print(lookup[frozenset([3, 2, 1])]) # numbers
print(hash(fs) == hash(frozenset([3, 2, 1]))) # TrueThis is useful when the identity of something is "a group of items, where order and repeats do not matter". Examples include a pair of nodes in an undirected graph, a combination of tags, or a set of required permissions.
edges = {
frozenset({"A", "B"}): 4,
frozenset({"B", "C"}): 7,
}
# The edge is the same whichever direction you name it.
print(edges[frozenset({"B", "A"})]) # 4
print(edges[frozenset(("C", "B"))]) # 7A tuple key such as ("A", "B") would treat ("B", "A") as a different key. The frozenset removes that problem.
Sets of sets
A regular set cannot contain sets, but it can contain frozensets. This lets you model collections of groups.
groups = {frozenset({1, 2}), frozenset({2, 1}), frozenset({3})}
print(len(groups)) # 2, the first two are equal
print(frozenset({1, 2}) in groups) # TrueConverting between set and frozenset
Conversion copies the elements into a new object. It is a shallow, one-level copy.
mutable = {1, 2, 3}
frozen = frozenset(mutable) # snapshot of the current contents
mutable.add(4)
print(sorted(frozen)) # [1, 2, 3]
print(sorted(mutable)) # [1, 2, 3, 4]
thawed = set(frozen) # a new, mutable copy
thawed.add(99)
print(sorted(frozen)) # [1, 2, 3]Using a frozenset as a constant
Because a frozenset cannot be altered, it is a good fit for a module-level constant. A shared set can be changed by any code that imports it, and the bug will be hard to trace. A frozenset turns that mistake into an immediate error.
ALLOWED_METHODS = frozenset({"GET", "POST", "PUT", "DELETE"})
def is_allowed(method):
return method.upper() in ALLOWED_METHODS
print(is_allowed("get")) # True
print(is_allowed("PATCH")) # FalseMembership tests are as fast as with a set. You get the safety without paying for it in speed.
Constant sets in `in` tests
When you write x in {1, 2, 3} with a literal of constants, CPython's compiler turns the literal into a frozenset and stores it once, instead of building a new set on every execution. You do not need to do anything to get this. It is an implementation detail of CPython, so do not depend on it in your own code.
Hashing details and edge cases
Hash depends on the elements, not the order
The hash of a frozenset is computed from the hashes of its elements in a way that does not depend on order. This is what makes frozenset([1, 2, 3]) and frozenset([3, 2, 1]) hash to the same value, as required for equal objects.
Immutable container, but not necessarily immutable contents
A frozenset only guarantees that its set of members cannot change. All elements must be hashable, and that is usually enough to make them effectively immutable. Hashable does not strictly mean immutable, though. An instance of a user-defined class is hashable by default, and it may carry mutable attributes. The frozenset keeps the same members, but those members can still change internally.
class Tag:
def __init__(self, name):
self.name = name
t = Tag("python")
fs = frozenset([t])
t.name = "changed"
print(next(iter(fs)).name) # changed
print(len(fs)) # 1This is safe as long as the hash and equality of the element do not depend on the attribute you change. The default object hash is based on identity, so here it is. If you define __eq__ and __hash__ using mutable fields and then change those fields, the frozenset will be in an inconsistent state, and lookups can fail.
Iteration order is still arbitrary
A frozenset has no defined order, just like a set. Use sorted() when you need predictable output. Do not assume that two frozensets with the same elements iterate in the same order.
Printing
The representation shows the type name. Since Python 3.x the elements in the output follow the internal table order, which can differ from insertion order.
fs = frozenset([1, 2, 3])
print(fs) # frozenset({1, 2, 3})
print(repr(frozenset())) # frozenset()Choosing between set and frozenset
Use these criteria to decide.
- Does the collection need to change after you build it? If yes, use
set. - Does it need to be a dict key or an element of another set? If yes, use
frozenset. - Is it a shared constant, or passed to code that must not modify it? Prefer
frozenset. - Is it built once and then only read? Either works, and
frozensetdocuments the intent.
There is a cost to consider. A frozenset gives you no way to add an element, so building up a large collection element by element needs a regular set first. Build the set, then convert once with frozenset(...) when you are done.
How the pieces fit together
Common mistakes
- Expecting
fs.add(x)to work. A frozenset has no mutating methods, so build a new one withfs | {x}. - Thinking
fs |= otherchanges the original object. It rebinds the name to a new frozenset. - Forgetting that the left operand decides the result type when you mix
setandfrozenset. - Using a
setas a dict key and gettingTypeError: unhashable type: 'set'. Wrap it withfrozenset(...). - Putting unhashable elements, such as lists, inside a frozenset.
Exercises
Exercise
You have a dictionary that maps a group of tags to a count, and you want counts[{"a", "b"}] to give the same answer as counts[{"b", "a"}]. Why does a plain set key fail, and what do you use instead?
Show answer
A set is mutable, so it is unhashable and raises TypeError: unhashable type: 'set' when used as a key. Use frozenset({"a", "b"}). Frozensets with the same elements are equal and have the same hash, so the order you list the elements in does not matter.
Exercise
What do type(s | f) and type(f | s) return when s = {1} and f = frozenset({2})?
Show answer
type(s | f) is set, and type(f | s) is frozenset. The result takes the type of the left operand.
Exercise
After running fs = frozenset({1, 2}); alias = fs; fs |= {3}, what are fs and alias, and why?
Show answer
fs is frozenset({1, 2, 3}) and alias is still frozenset({1, 2}). A frozenset has no in-place union, so fs |= {3} becomes fs = fs | {3}, which creates a new object and rebinds fs. The object that alias refers to is unchanged.