← Back to Python Course | Chapter 11: Advanced Python | Lesson 10 of 12

Python Enum

What is an Enum?

An Enum groups a fixed set of named constants under one type, created by subclassing Enum from the enum module. Replacing scattered magic strings or integers (like status = 2) with named members (status = Status.SHIPPED) makes code both more readable and safer, since typos in a string literal won't be caught by anything but a member name will.

Example: What is an Enum?

python
from enum import Enum

class Status(Enum):
    PENDING = 1
    SHIPPED = 2

status = Status.SHIPPED
print(status)

Iterating Over Enums

Iterating over an Enum class (for status in Status:) walks through every defined member in declaration order, giving you each name and its underlying value. This is handy for building validation lists, populating dropdown choices, or generating documentation without hand-maintaining a separate list of valid values.

Example: Iterating Over Enums

python
from enum import Enum

class Status(Enum):
    PENDING = 1
    SHIPPED = 2

for status in Status:
    print(status.name, status.value)

Unique Enum Values

By default, Python allows two Enum names to alias the same underlying value without complaint, which can hide bugs where you meant to define two genuinely distinct states. Decorating the class with @unique makes Python raise a ValueError at class-definition time if any two members share a value.

Example: Unique Enum Values

python
from enum import Enum, unique

@unique
class Status(Enum):
    PENDING = 1
    SHIPPED = 2

print("No duplicate values allowed")

Enum Comparisons

Enum members compare by identity or equality against each other (Status.ACTIVE == Status.ACTIVE) but not against plain integers or strings unless you specifically inherit from IntEnum or StrEnum. This strictness is intentional -- it stops you from accidentally comparing an enum member to an unrelated raw value that happens to match.

Example: Enum Comparisons

python
from enum import Enum

class Status(Enum):
    ACTIVE = 1
    INACTIVE = 2

print(Status.ACTIVE == Status.ACTIVE)
print(Status.ACTIVE == 1)

Automatic Values

When the specific numeric values of your enum members don't matter -- only that each is unique -- auto() assigns sequential integers starting from 1 automatically. This saves you from manually numbering members and renumbering everything whenever you insert a new one in the middle.

Example: Automatic Values

python
from enum import Enum, auto

class Status(Enum):
    PENDING = auto()
    SHIPPED = auto()

print(Status.PENDING.value, Status.SHIPPED.value)

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.