What is a frozenset, and why would you use it instead of a set?
Answer
A frozenset is an immutable, hashable version of a set: once created, elements cannot be added or removed. Because it is hashable, a frozenset can be used as a dict key or as a member of another set, which a regular mutable set cannot. It is the right choice whenever a fixed collection of unique values needs to act as a lookup key, such as caching a function's result keyed by an unordered set of input flags.
Strong answer includes
- immutable, hashable variant of set
- usable as a dict key or set member
- fits fixed collections used as lookup keys
Practical example
cache = {}keyed by
frozenset(active_flags)lets a memoization layer treat
{"a", "b"}and
{"b", "a"}as the same cache key regardless of insertion order.