Note
This feature uses the concept of bit masks, often referred to as ‘flags’. Flags are a common technique to efficiently store multiple boolean options in a single integer value. Flags can be built and modified using bitwise operations.
See Details
# Our bit mask constants, we define them here in binary to make more obvious what happens:
# The flipped bit travels forwards and flags never use the same bit twice. Another way of
# looking at this, would be to say that each flag represents a unique power of two. In
# practice, such values are often defined as decimal or hex values and not in binary.
MASK_NONE : int = 0b0000 # i.e., 0 in decimal
MASK_VISIBLE : int = 0b0001 # i.e., 1 in decimal
MASK_LOCKED : int = 0b0010 # i.e., 2 in decimal
MASK_SELECTED: int = 0b0100 # i.e., 4 in decimal
# Now we can express multiple things in one value by setting these masks.
myValue: int = MASK_VISIBLE | MASK_LOCKED # i.e., 0b0011 in binary.
# Which we then can test for like this (or a bit more verbose bool(value & MASK) == True).
if myValue & MASK_VISIBLE:
print("myValue is visible")
if myValue & MASK_LOCKED:
print("myValue is locked")
if not myValue & MASK_SELECTED:
print("myValue is not selected")
# Flags can be set with bitwise OR and removed with bitwise AND NOT.
myValue = myValue | MASK_SELECTED # Set the selected flag
myValue = myValue & ~MASK_LOCKED # Remove the locked flag