Show how a Python frozenset differs from a normal set, including using one as a dictionary key.
A frozenset is an immutable set. It holds unique hashable items and supports all the read operations of a set, but none of the mutating ones.
frozen = frozenset({1, 2, 3})
print(type(frozen).__name__) # frozenset
print(sorted(frozen)) # [1, 2, 3]
# It can be a dictionary key, because it is hashable
cache = {frozen: "cached value"}
print(cache[frozenset({3, 2, 1})]) # cached value
try:
cache[set([1, 2, 3])]
except TypeError as err:
print("TypeError:", err)The dictionary lookup with a freshly built frozenset succeeds, because a frozenset hashes by its contents and two frozensets with the same elements are equal and hash the same. The lookup with a plain set fails with a TypeError saying that a set is unhashable, which is the key difference between the two types.
Note that the frozenset has no add method at all, rather than having one that raises. The mutating methods of a set simply do not exist on a frozenset, so trying to call one gives an AttributeError. The operations that do work are the read ones: membership tests, len, iteration, and the union, intersection, difference and symmetric difference operations, which all return new frozensets.