Python - Enums

Overview

Estimated time: 15–25 minutes

enum.Enum and enum.IntFlag provide readable, type-safe constants and bit flags in Python.

Learning Objectives

  • Define Enum/IntEnum and IntFlag.
  • Use auto() and iterate members.
  • Apply IntFlag for bit-mask style flags.

Examples

from enum import Enum, IntFlag, auto

class Color(Enum):
    RED = auto()
    GREEN = auto()
    BLUE = auto()

print(Color.RED.name, Color.RED.value)

class Perm(IntFlag):
    READ = 1
    WRITE = 2

p = Perm.READ | Perm.WRITE
print(Perm.READ in p)

Guidance & Patterns

  • Prefer enums over bare constants for clarity and validation.
  • Use IntFlag when combining flags with bitwise ops.

Best Practices

  • Serialize by name for stability across versions; map names to values.

Exercises

  1. Create an enum for order states and a function that validates transitions.
  2. Implement permissions using IntFlag and check membership.