Sub topic 10
Combining Options with Flag
This chapter assumes you can define an Enum, use auto(), and compare members with == and is. It also assumes you know that integers are stored as bits. The examples assume Python 3.11 or later. Where earlier versions behave differently, the text says so.
The problem Flag solves
A plain Enum member represents exactly one choice. A function can take Color.RED or Color.BLUE, but not "red and blue at once". Many settings are not like that. A file can be readable and writable. A regular expression can be case-insensitive and multiline. A user can hold several permissions.
The traditional answer is a set of integer constants that each use one bit, combined with the bitwise OR operator. Flag gives you that technique with named members, a readable repr, and type checking.
Defining a Flag
Subclass Flag and let auto() pick the values. For Flag, auto() produces powers of two (1, 2, 4, 8, and so on), so each member owns one bit.
from enum import Flag, auto
class Perm(Flag):
READ = auto()
WRITE = auto()
EXECUTE = auto()
print([p.value for p in Perm]) # [1, 2, 4]
rw = Perm.READ | Perm.WRITE
print(rw) # Perm.READ|WRITE
print(rw.value) # 3
print(type(rw)) # <enum 'Perm'>The combination rw is not a new class. It is a Perm instance whose value is 1 | 2 = 3. Python creates it on demand and caches it, so Perm.READ | Perm.WRITE is Perm(3) is True.
Operators
Flag supports the four bitwise operators. Each takes Flag operands of the same class and returns a member of that class.
| Operator | Meaning | Example | Result value | Column | Column |
|---|---|---|---|---|---|
| `a \ | b` | Union: bits set in either | `Perm.READ \ | Perm.WRITE` | 3 |
| `a & b` | Intersection: bits set in both | `rw & Perm.WRITE` | 2 | ||
| `a ^ b` | Symmetric difference: bits set in exactly one | `rw ^ Perm.WRITE` | 1 | ||
| `~a` | Complement within the defined bits | `~Perm.READ` | 6 |
from enum import Flag, auto
class Perm(Flag):
READ = auto()
WRITE = auto()
EXECUTE = auto()
rw = Perm.READ | Perm.WRITE
print((rw & Perm.WRITE).value) # 2
print((rw ^ Perm.WRITE).value) # 1
print((~Perm.READ).value) # 6
print((rw & Perm.EXECUTE).value) # 0The complement stays inside the bits that the class defines. ~Perm.READ is WRITE|EXECUTE (value 6), not a negative number as it would be with a plain int. Flags are immutable. The statement perms |= Perm.EXECUTE builds a new member and rebinds the name. It does not change the old one.
Testing membership
Use in to ask whether a flag is contained in a combination.
from enum import Flag, auto
class Perm(Flag):
READ = auto()
WRITE = auto()
EXECUTE = auto()
rw = Perm.READ | Perm.WRITE
print(Perm.READ in rw) # True
print(Perm.EXECUTE in rw) # False
print((Perm.READ | Perm.WRITE) in rw) # True
print((Perm.READ | Perm.EXECUTE) in rw) # FalseWhen the left operand has several bits, in requires all of them. Writing a in b is equivalent to a & b == a. If you want "at least one of these", test the intersection. An empty flag is falsy and any other flag is truthy.
from enum import Flag, auto
class Perm(Flag):
READ = auto()
WRITE = auto()
EXECUTE = auto()
granted = Perm.WRITE | Perm.EXECUTE
wanted_any = Perm.READ | Perm.WRITE
if granted & wanted_any:
print("at least one wanted permission is granted") # printedUsing in with a value that is not a member of the same class raises TypeError. 3 in Perm.READ does not work. That is a useful safeguard, and IntFlag, covered below, relaxes it.
The empty flag and invalid values
The value 0 means "no flags set". Calling Perm(0) returns a member with no bits, even though you never defined a name for it. It is falsy.
from enum import Flag, auto
class Perm(Flag):
READ = auto()
WRITE = auto()
EXECUTE = auto()
none = Perm(0)
print(none.value) # 0
print(bool(none)) # False
print(Perm(3).value) # 3, the same member as READ|WRITE
try:
Perm(8)
except ValueError:
print("8 uses a bit that Perm does not define")Perm(8) fails because bit 3 belongs to no member. Flag uses the STRICT boundary mode by default. Every bit in the value must belong to some defined member. This catches stale or corrupted data when you rebuild flags from stored integers.
Named combinations
You can give a common combination its own name. Inside the class body the earlier names are still plain integers, so you combine them with | as numbers.
from enum import Flag
class Perm(Flag):
EXECUTE = 1
WRITE = 2
READ = 4
RW = READ | WRITE
ALL = READ | WRITE | EXECUTE
print(Perm.RW.value) # 6
print(Perm.READ in Perm.ALL) # True
print(list(Perm)) # [<Perm.EXECUTE: 1>, <Perm.WRITE: 2>, <Perm.READ: 4>]
print(list(Perm.RW)) # [<Perm.WRITE: 2>, <Perm.READ: 4>]From Python 3.11, iterating over the class yields only the single-bit members, which are called canonical members. Named combinations such as RW and ALL exist and can be looked up, but they are skipped. In Python 3.10 and earlier they are included in the iteration. Also from 3.11, iterating over one flag value yields its single-bit parts, so list(Perm.RW) splits RW into WRITE and READ. Use this to loop over whatever a particular value contains.
Adding behavior
Flags are ordinary enum classes, so methods and properties work as before. Here is a method that formats a value in the style of Unix permissions.
from enum import Flag, auto
class Perm(Flag):
READ = auto()
WRITE = auto()
EXECUTE = auto()
def symbols(self):
pairs = (("r", Perm.READ), ("w", Perm.WRITE), ("x", Perm.EXECUTE))
return "".join(letter if flag in self else "-" for letter, flag in pairs)
print((Perm.READ | Perm.WRITE).symbols()) # rw-
print(Perm.EXECUTE.symbols()) # --x
print(Perm(0).symbols()) # ---Storing and restoring flags
To save a flag in a database or JSON file, store its .value. To restore it, pass the integer back to the class.
from enum import Flag, auto
class Perm(Flag):
READ = auto()
WRITE = auto()
EXECUTE = auto()
saved = (Perm.READ | Perm.EXECUTE).value
print(saved) # 5
restored = Perm(saved)
print(restored is (Perm.READ | Perm.EXECUTE)) # TrueBecause the stored integer depends on the order of definition, never reorder or insert members in the middle of a persisted Flag. Append new members at the end, or assign explicit values.
IntFlag: flags that are also integers
IntFlag combines int and Flag. Its members are integers, so they interoperate with code that expects plain numbers, such as C libraries and the os and re modules. Operations between an IntFlag and an int return an IntFlag.
from enum import IntFlag
class Mode(IntFlag):
X = 1
W = 2
R = 4
combined = Mode.R | Mode.W
print(combined == 6) # True
print(Mode.R | 1 == 5) # True
print(Mode(5).value) # 5
print(Mode(8).value) # 8The last line shows a difference from Flag. IntFlag uses the KEEP boundary mode, so Mode(8) is accepted and keeps the unknown bit. Plain Flag raises ValueError for the same input.
Choose Flag when the options are meant to be used only through the enum, because it gives you stricter type safety and errors for stray values. Choose IntFlag only when you must pass the values to code that works with raw integers.
Common mistakes
- Using
infor "any of".(A | B) in valueneeds both bits. Usebool(value & (A | B))instead. - Assuming zero is a named member.
Perm(0)works, but it has no name. If you want to writePerm.NONE, define it yourself asNONE = 0. - Comparing with
==to test one flag.value == Perm.READis true only whenREADis the only bit set. UsePerm.READ in value. - Non-power-of-two values. If you assign values by hand, make single-bit members powers of two. A member with value 3 is treated as a combination of bits 1 and 2, not as a new independent option.
- Iterating and expecting combinations. Since 3.11,
list(Perm)omits named combinations. On older versions it includes them. Check your Python version if the output surprises you. - Mixing classes.
Perm.READ | Other.FLAGraisesTypeErrorforFlag, because members of different enum classes cannot be combined.
Exercise
Define Feature(Flag) with members A, B and C created with auto(). Let enabled = Feature.A | Feature.C. What is (enabled ^ Feature.A).value, and what is (enabled & Feature.B).value?
Show answer
auto() gives A = 1, B = 2 and C = 4, so enabled has value 5. XOR with A removes bit 1 and leaves only C, so the first value is 4. enabled does not include B, so the intersection is empty and the second value is 0.
Exercise
A function receives granted and required, both Perm values. Write one expression that is true only when granted contains every flag in required, and another that is true when it contains at least one flag from required.
Show answer
Every flag: required in granted. At least one flag: bool(granted & required). The first works because in checks that all bits of required are set in granted. The second works because the intersection is falsy only when the two values share no bits.