Use reduce to combine permission flags
Also published in our Blogger archive.
Use reduce to combine permission flags
A permission set is naturally represented as bits when each capability has one distinct power-of-two value. Permission.READ is 1, WRITE is 2, and EXECUTE is 4. The bitwise OR operator combines bits without discarding already-granted capabilities. In this example, read plus execute becomes integer mask 5.
functools.reduce applies operator.or_ from left to right across the selected flags. Passing Permission(0) as initial matters: it is the identity value for OR and provides a sensible result for an empty selection. Without it, reduce raises TypeError for an empty list. The two assertions establish the selected bits for this specific input: read and execute are present, while write is absent.
This combination answers “which capabilities are in this collection?”, not “may this actor perform an action?” Authorization may also require ownership, expiry, tenant checks, or an explicit deny rule. IntFlag is convenient for readable combinations, but it does not automatically validate unrecognised bits supplied from an untrusted integer. Validate external masks against an allowed mask before using them for access decisions. For a sequence where intermediate masks are useful, itertools.accumulate is a better match than reduce.
AI assistance disclosure: This article was prepared with AI assistance.
Example
from enum import IntFlag
from functools import reduce
from operator import or_
class Permission(IntFlag):
READ = 1
WRITE = 2
EXECUTE = 4
requested = [Permission.READ, Permission.EXECUTE]
combined = reduce(or_, requested, Permission(0))
assert combined == Permission.READ | Permission.EXECUTE
assert combined & Permission.WRITE == Permission(0)
print(int(combined))
Expected output
5