Show how a Python frozenset differs from a normal set, including using one as a dictionary key.
A frozenset is a set that cannot be changed. It holds unique hashable items and it supports every read operation of a normal set, but it has none of the operations that change a set.
frozen = frozenset({1, 2, 3})
print(type(frozen).__name__)
print(sorted(frozen))
# It can be a dictionary key, because it can be hashed.
cache = {frozen: 'cached value'}
print(cache[frozenset({3, 2, 1})])
try:
cache[set([1, 2, 3])]
except TypeError as error:
print('TypeError:', error)
The dictionary lookup with a freshly built frozenset works, because a frozenset hashes by its contents, so two frozensets that hold the same items are equal and hash to the same value. The lookup with a normal set fails with a TypeError that says a set cannot be hashed, and that failure is the main difference between the two types.
Notice that a frozenset does not have an add method at all, rather than having one that raises an error. The changing methods of a set simply do not exist on a frozenset, so trying to call one gives you an AttributeError. The operations that do work are the reading ones, which means membership tests, len, going through the items, and the union, intersection, difference, and symmetric difference operations. Each of those gives you a brand new frozenset.