frozenset#
frozenset is the immutable, hashable sibling of set.
Same set-algebra surface; can sit inside another set or as a
dict key. Reach for it when the membership of a group is
fixed at construction.
roles = frozenset({"read", "write", "admin"})
"read" in roles # True
roles | frozenset({"audit"}) # new frozenset
d = {roles: "policy-A"} # frozenset as key
No add / remove / pop; every operation that would
change the set returns a new frozenset.
Use frozenset for caller-facing constants
(ALLOWED_METHODS = frozenset({"GET", "POST"})) so a downstream
mutation can’t break the invariant.
Method catalog#
frozenset inherits the read-only set-algebra and predicate
methods from set; the in-place mutators are absent.
Method |
Effect |
|---|---|
|
New frozenset; same as |
|
New frozenset; same as |
|
New frozenset; same as |
|
New frozenset; same as |
|
Shallow copy. |
|
|
|
Every element is in |
|
Every element of |
union and intersection return new frozensets; they
accept any iterable, the operators require frozensets on both
sides.
frozenset({1, 2}).union([2, 3, 4])
frozenset({1, 2, 3, 4})
difference filters this set against any iterable.
frozenset({1, 2, 3, 4}).difference([2, 4])
frozenset({1, 3})
issubset mirrors the <= operator.
frozenset({1, 2}).issubset({1, 2, 3})
True
Operator overloading#
frozenset implements the read-only set-algebra dunders. The
in-place dunders (__ior__, __iand__, etc.) are absent.
Operator |
Dunder |
Returns |
|---|---|---|
|
|
New frozenset (union). |
|
|
New frozenset (intersection). |
|
|
New frozenset (difference). |
|
|
New frozenset (symmetric difference). |
|
|
Subset test. |
|
|
Proper subset. |
|
|
Equality. |
|
|
Membership. |
|
|
Cardinality. |
|
|
Iteration. |
|
|
Hash for set / dict membership. |
|
|
|
A frozenset is hashable, so it can sit as a dict key.
policy = {frozenset({"read"}): "ro", frozenset({"read", "write"}): "rw"}
policy[frozenset({"read", "write"})]
'rw'
Set algebra returns a new frozenset; the original is
unchanged.
a = frozenset({1, 2, 3}); b = frozenset({3, 4})
a | b, a
(frozenset({1, 2, 3, 4}), frozenset({1, 2, 3}))