check if enum flag is set in python

In Python, enums can be defined using the Enum class from the enum module. Enum flags are essentially integers that can have multiple bit positions set, just like bit flags in C++ or C#. Here's how you can check if a specific bit position is set in an enum flag in Python:

main.py
from enum import Enum

class MyEnum(Enum):
    FLAG_A = 1   # 0b0001
    FLAG_B = 2   # 0b0010
    FLAG_C = 4   # 0b0100
    FLAG_D = 8   # 0b1000

# define an enum flag with some bits set
my_flag = MyEnum.FLAG_A | MyEnum.FLAG_C   # 0b0101

# check if bit position for FLAG_A is set
if my_flag & MyEnum.FLAG_A:
    print("FLAG_A is set")

# check if bit position for FLAG_B is set
if my_flag & MyEnum.FLAG_B:
    print("FLAG_B is set")

# check if bit position for FLAG_C is set
if my_flag & MyEnum.FLAG_C:
    print("FLAG_C is set")

# check if bit position for FLAG_D is set
if my_flag & MyEnum.FLAG_D:
    print("FLAG_D is set")
632 chars
27 lines

In the code above, we define an enum class MyEnum with four flags, FLAG_A to FLAG_D, whose bit positions are 1, 2, 4 and 8, respectively. We define an example value for my_flag with the bit positions for FLAG_A and FLAG_C set.

To check if a specific bit position is set in my_flag, we use the bitwise AND operator (&) to compare the flag value with the corresponding enum flag value. If the result is non-zero, then the bit position for that flag is set in the enum flag value. This allows us to selectively test which flags are set in the enum flag value.

gistlibby LogSnag