🐍 Python Intermediate

What is Python's enum module?

Answer

The enum module (Python 3.4+) provides a formal way to define named constants. from enum import Enum, auto; class Color(Enum): RED = 1; GREEN = 2; BLUE = 3. Access: Color.RED (member), Color.RED.value (1), Color.RED.name ("RED"). Iterate: list(Color). Check membership: isinstance(Color.RED, Color). auto() assigns sequential values automatically. IntEnum: behaves like int in comparisons. Flag/IntFlag: for bitwise operations (permissions): class Perm(Flag): READ = auto(); WRITE = auto(); EXECUTE = auto(); RW = READ | WRITE. StrEnum (Python 3.11+): string-valued enum. Enums are iterable, comparable, and hashable — use them as dict keys. They replace magic number/string constants with readable, type-safe values. Enums work well with match/case (Python 3.10+) for exhaustive pattern matching.