Member-only story
The Enum Trick Every Python Developer Should Know
Learn how Python’s Enum can simplify constants, improve code readability, and add smart behavior to your projects. A must-know trick for developers!
You ever write some code, think it’s clean, and then come back a month later wondering what on earth past-you was thinking? Yeah, me too.
A while ago, I was working on a project that had different user roles — admin, editor, viewer. Nothing complicated. I took the classic “define everything as constants” approach:
ADMIN = 1
EDITOR = 2
VIEWER = 3
It worked. No complaints. Until, of course, the codebase started growing, and suddenly, I had hardcoded numbers scattered everywhere.
if role in [ADMIN, EDITOR]:
print("User can edit content")
I knew this wasn’t the best way, but hey, it got the job done — until it didn’t. Adding new roles meant modifying multiple places, and debugging got painful. That’s when I stumbled (again) on Python’s Enum.
Why Constants Fall Apart Quickly?
Defining roles as plain constants seems fine at first, but it comes with a few annoying issues:
- Magic numbers — If you see
if role == 1
, you have no clue what1
actually represents.