Learn Python
>>> oop_advanced.enums

Enums in Python

#concept

An enum (enumeration), from the enum module, defines a fixed, named set of related constant values — like the days of the week or a set of valid statuses — giving each one a readable name instead of a bare number or string that's easy to mistype. Comparing against an enum member is safer and clearer than comparing against a plain string or magic number scattered throughout code.

#how it works
1

Import Enum

From the enum module, part of the standard library.

2

Define an enum by subclassing Enum

Listing each member as a name assigned to a value.

3

Access members through the enum itself

Status.ACTIVE, not the raw underlying value.

4

Compare members directly with ==

Checks identity of the named member, not just an equal underlying value.

5

.name and .value expose the details

A member’s name and its underlying stored value, when needed.

#example
from enum import Enum
 
class Status(Enum):
ACTIVE = 1
INACTIVE = 2
PENDING = 3
 
current = Status.ACTIVE
 
print(current)
print(current.name, current.value)
print(current == Status.ACTIVE)
Output
Status.ACTIVE
ACTIVE 1
True
1class Status(Enum): defines three related, named constants in one place.
2current = Status.ACTIVE assigns a specific, readable member, rather than the bare number 1.
3Printing current shows Status.ACTIVE, a clear label rather than a plain integer.
4current.name and current.value pull out the member’s name and underlying stored value separately.
5current == Status.ACTIVE compares by the actual named member, which is much harder to get subtly wrong than comparing raw numbers.
#use cases
Representing a fixed set of valid states, like an order's Status: PENDING, SHIPPED, DELIVERED
Replacing 'magic numbers' or loose string comparisons scattered through a codebase with clear, checkable names
Making invalid values impossible to represent by accident, since only the defined members exist
Improving autocomplete and readability wherever a limited, known set of options is being represented

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.