Python Topics : Enums
Accessing Enums
from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

# direct access
print(Color.RED)
# access the enum's value
print(Color.GREEN.value)
# lookup enum by value
print(Color(2))
# key lookup
print(Color["RED"])
output
Color.RED
2
Color.GREEN
Color.RED
Benefits to Using Enums
improved readability provides meaningful names for constant values
reduced errors avoids literal names for constant values
reduces chance of value and typographical errors
namespace organization groups similar constants together
Types of Enums
Enum base class for simple enums
IntEnum subclass of Enum
members are integers
can be used as integers
from enum import IntEnum

class Status(IntEnum):
    SUCCESS = 1
    FAILURE = 2
    PENDING = 3

def check_status(status):
    if status == Status.SUCCESS:
        print("Operation was successful!")

check_status(1)  # Works because Status.SUCCESS is also an integer
Flag subclass of Enum
members can be combined using bitwise operations
sample below demonstrates use of both Flag and IntFlag
auto() method allows the Enum class to automatically generate the numerical value for the enum's member
from enum import Flag, auto

class Permission(Flag):
    READ = auto()
    WRITE = auto()
    EXECUTE = auto()

# Combining flags
perms = Permission.READ | Permission.WRITE
print(perms)
print(Permission.READ in perms)
output
Permission.READ|WRITE
True
IntFlag a combination of IntEnum and Flag
Extending Enum Functionality
since an Enum is a class it can have class methods
from enum import Enum

class Weekday(Enum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3
    THURSDAY = 4
    FRIDAY = 5
    SATURDAY = 6
    SUNDAY = 7

    def is_weekend(self):
        return self in (Weekday.SATURDAY, Weekday.SUNDAY)

print(Weekday.SATURDAY.is_weekend())
print(Weekday.WEDNESDAY.is_weekend())
output
True
False
Custom Values
custom values can be added to an enum
an enum's value attribute is protected
class Color(Enum):
    RED = 1, (255, 0, 0)
    GREEN = 2, (0, 255, 0)
    BLUE = 3, (0, 0, 255)

    def __init__(self, value, rgb):
        self.value = value  # Attribute Error: Cannot set 'value'
        self.rgb = rgb
to set the value use the _value_ attribute
class Color(Enum):
    RED = 1, (255, 0, 0)
    GREEN = 2, (0, 255, 0)
    BLUE = 3, (0, 0, 255)

    def __init__(self, value, rgb):
                self._value_ = value
        self.rgb = rgb

print(Color.RED)
print(Color.RED.value)
print(Color.RED.rgb)
output
Color.RED
1
(255, 0, 0)
index