Reject unknown flag bits with IntFlag STRICT
IntFlag normally keeps unknown bits. For a schema that accepts only declared flag bits, set boundary=STRICT and handle ValueError at the input boundary.
Run the example
Tested on Linux with Python 3.12.14. No third-party packages or network access are needed. In one Bash session, create a temporary working directory:
demo_start="$PWD"
demo_dir="$(mktemp -d)" || exit 1
cd -- "$demo_dir" || exit 1Save as demo_strict_flags.py in that directory. Use this filename to avoid shadowing a standard-library module.
from enum import IntFlag, STRICT
class Mode(IntFlag, boundary=STRICT):
READ = 1
WRITE = 2
class FlexibleMode(IntFlag):
READ = 1
WRITE = 2
for raw in (0, 1, 3, 4, 5):
try:
mode = Mode(raw)
except ValueError:
print(raw, "rejected")
else:
print(raw, "accepted", mode.name)
print("Default keeps:", int(FlexibleMode(5)))Run it:
python3 demo_strict_flags.pyCaptured output:
0 accepted None
1 accepted READ
3 accepted READ|WRITE
4 rejected
5 rejected
Default keeps: 5Interpret the result
Zero and combinations of declared bits are accepted. Values containing bit 4 are rejected even when another bit is valid. Strict boundaries were added in Python 3.11. They validate the allowed bit mask, not every business rule: if READ and WRITE must be mutually exclusive, validate that separately. Choose an explicit policy for future protocol bits; silently ignoring them can hide a producer/consumer mismatch. If your input schema requires nonnegative integers, validate that independently rather than relying on flag construction alone.
See the version-specific Python reference for the API contract.
Clean up
In the same Bash session, remove the source file and then the empty working directory:
rm -- demo_strict_flags.py
cd -- "$demo_start" || exit 1
rmdir -- "$demo_dir"
unset demo_start demo_dirIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.