Programming

Enums in Python: The Constant That Reads Like a Name

Enums in Python: The Constant That Reads Like a Name
Photo by Nick Hillier / Unsplash

An enum replaces a bare string or magic number with a name the language can check. role == "admin" compiles fine with a typo; role == Role.Admni fails loudly. That difference is the whole argument.

What an Enum gives you

from enum import Enum

class Role(Enum):
    ADMIN = "admin"
    MODERATOR = "moderator"
    USER = "user"

Now the value is a member, not a string. It's iterable (list(Role)), it's comparable by identity, it has a .name and a .value, and a wrong name raises AttributeError instead of silently mismatching. Roles, states, statuses — anywhere a constant would have been a string someone mistyped.

The variants worth knowing

IntEnum members behave like ints — sortable, arithmetic-able, useful when the value must interoperate with code that expects numbers (exit codes, protocol fields, database enums stored as integers). Flag and IntFlag are bitwise: combine members with | for permission sets. Permission.READ | Permission.WRITE is one value, not two.

Where they earn their keep

Web-app roles are the classic case — the string "admin" scattered through a codebase is a typo waiting to happen. State machines, API status fields, config choices: anywhere a value is selected from a fixed set, an enum is the honest type. The set is enumerable, so "what are the valid options" is a question the code answers itself.

When it breaks

The mistake is reaching for Enum when the set isn't fixed. A list that grows at runtime — user-defined tags, tenant-provided values — fights the enum. Use it when the options are yours, not when they're data.

$ tail -f /forums

Discussion

Comments live on the community forums — sign in there to reply.