Reject unknown flag bits at a runtime boundary
Also published in our Blogger archive.
An integer received from a file, request decoder, or database column is a runtime boundary: it may contain bits this version of the program does not define. Convert it only after checking the representation and mask. decode_access() first requires an exact built-in int, rejects negatives, then calculates whether any set bit lies outside KNOWN_MASK. The raw & ~KNOWN_MASK expression is zero only when every selected bit is known.
The accepted input 5 maps to READ | EXPORT. Input 8 is rejected because no member owns that bit; True is rejected deliberately because bool is an int subclass but is not an intended wire-format integer here. The assertions show the accepted conversion and the printed messages make both failures visible.
This explicit guard matters because IntFlag normally preserves unknown bits under its default KEEP boundary behavior. It is a format-validation rule, not proof that the integer came from a trusted source or that its capabilities are authorized. IntFlag is available from Python 3.6; see the official enum documentation for flag boundaries and integer-flag behavior.
AI-assistance disclosure: this article was drafted with AI assistance and should be reviewed against the protocol’s compatibility policy.
from enum import IntFlag
class Access(IntFlag):
READ = 1
WRITE = 2
EXPORT = 4
KNOWN_MASK = int(Access.READ | Access.WRITE | Access.EXPORT)
def decode_access(raw: object) -> Access:
if type(raw) is not int or raw < 0:
raise ValueError("access must be a non-negative integer")
if raw & ~KNOWN_MASK:
raise ValueError("access contains unknown bits")
return Access(raw)
assert decode_access(5) == Access.READ | Access.EXPORT
for raw in (8, True):
try:
decode_access(raw)
except ValueError as error:
print(f"{raw!r}: {error}")
print(f"accepted={int(decode_access(5))}")
8: access contains unknown bits
True: access must be a non-negative integer
accepted=5