Sub topic 10
Combining options with Flag
This chapter assumes you know how to define an Enum, how auto() assigns values, and how Python's bitwise operators (|, &, ~) work on integers. The examples use Python 3.11 or later.
The problem Flag solves
A plain Enum represents one choice out of several. Some settings are different: a file can be readable and writable at the same time. You could use a list or set of enum members, but Flag gives you a single value that holds any combination of options.
A Flag member's value is treated as a set of bits. Each basic member uses one bit, and combining members sets several bits at once.
Defining and combining flags
When you use auto() in a Flag, Python assigns powers of two: 1, 2, 4, 8, and so on. Each member then owns exactly one bit.
from enum import Flag, auto
class Perm(Flag):
READ = auto()
WRITE = auto()
EXECUTE = auto()
RW = READ | WRITE # a named combination
rw = Perm.READ | Perm.WRITE
print(rw.value) # 3
print(rw is Perm.RW) # True
print(Perm.READ in rw) # True
print(Perm.EXECUTE in rw) # False
perms = Perm.RW | Perm.EXECUTE
perms &= ~Perm.WRITE # remove one option
print(perms.value) # 5
print(bool(Perm(0))) # FalseRW is a named combination. Its value, 3, matches READ | WRITE, so combining those two members gives you the same RW object. Because RW is not a single-bit member, it counts as an alias for a combination and does not appear when you iterate over the class.
The operators
| Operator | Meaning | Example | Column | Column |
|---|---|---|---|---|
| `a \ | b` | Union: every option in either operand | `Perm.READ \ | Perm.WRITE` |
| `a & b` | Intersection: options present in both | `Perm.RW & Perm.READ` is `Perm.READ` | ||
| `a ^ b` | Options present in exactly one operand | `Perm.RW ^ Perm.READ` is `Perm.WRITE` | ||
| `~a` | Every defined option that is not in `a` | `~Perm.READ` is `WRITE` plus `EXECUTE` | ||
| `a in b` | True if all options of `a` are in `b` | `Perm.READ in Perm.RW` |
Empty flags and iteration
A flag with value 0 means "no options". It is falsy, so you can test whether any option is set.
from enum import Flag, auto
class Perm(Flag):
READ = auto()
WRITE = auto()
EXECUTE = auto()
none = Perm.READ & Perm.WRITE
print(bool(none)) # False
both = Perm.READ | Perm.WRITE
print([m.name for m in both]) # ['READ', 'WRITE']
try:
Perm(8)
except ValueError:
print("bit 8 is not defined")In Python 3.11 and later, iterating over a combined value yields its single-bit members. Iterating over the class itself yields only the single-bit members too.
A plain Flag is strict about unknown bits. Perm(8) raises ValueError because no member owns that bit.
IntFlag: flags that are also integers
IntFlag works like Flag, but members are real integers. This makes it a good fit for values that must interoperate with integer APIs, such as file modes or OS constants.
from enum import IntFlag
class Mode(IntFlag):
R = 4
W = 2
X = 1
combined = Mode.R | Mode.W
print(int(combined)) # 6
print((Mode.R | 1) == 5) # True
print(combined == 6) # TrueWith Flag, mixing a member and a plain integer raises TypeError. With IntFlag, it works, and the result is an IntFlag member. The cost is the same one you saw with IntEnum: members compare equal to unrelated integers, so type mistakes are easier to make.
Choosing values by hand
auto() is convenient, but you can assign explicit values when they must match an external format. Use powers of two for single-bit members, and use combined values only for named combinations. If two single-bit members share a bit, or a value is not a power of two, you have created a combination, not a basic option.
Exercise
Using the Perm class from the second example, write a line that removes EXECUTE from a variable p that may or may not contain it, and explain why it is safe when EXECUTE is absent.
Show answer
p &= ~Perm.EXECUTE. The ~Perm.EXECUTE expression is every defined option except EXECUTE. Intersecting p with it keeps all options except EXECUTE. If EXECUTE was not in p, the intersection leaves p unchanged, so no error occurs.
Exercise
Why would Flag raise TypeError for Perm.READ | 4, while IntFlag accepts the same kind of expression?
Show answer
A Flag member is not an integer, so it only combines with members of the same class. An IntFlag member is a subclass of int, so it can combine with plain integers and the result is converted back to an IntFlag.