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

union(*others)

New frozenset; same as a | b.

intersection(*others)

New frozenset; same as a & b.

difference(*others)

New frozenset; same as a - b.

symmetric_difference(other)

New frozenset; same as a ^ b.

copy()

Shallow copy.

isdisjoint(other)

True when no common elements.

issubset(other)

Every element is in other.

issuperset(other)

Every element of other is in self.

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

a | b

__or__

New frozenset (union).

a & b

__and__

New frozenset (intersection).

a - b

__sub__

New frozenset (difference).

a ^ b

__xor__

New frozenset (symmetric difference).

a <= b

__le__

Subset test.

a < b

__lt__

Proper subset.

a == b

__eq__

Equality.

x in a

__contains__

Membership.

len(a)

__len__

Cardinality.

iter(a)

__iter__

Iteration.

hash(a)

__hash__

Hash for set / dict membership.

bool(a)

__bool__

False only for the empty frozenset.

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}))

References#