Python in Plain English

New Python content every day. Follow to join our 3.5M+ monthly readers.

Follow publication

Member-only story

The Enum Trick Every Python Developer Should Know

Vijay
Python in Plain English
5 min read6 days ago

--

Learn how Python’s Enum can simplify constants, improve code readability, and add smart behavior to your projects. A must-know trick for developers!

Photo by Hitesh Choudhary on Unsplash

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:

  1. Magic numbers — If you see if role == 1, you have no clue what 1 actually represents.

--

--

Published in Python in Plain English

New Python content every day. Follow to join our 3.5M+ monthly readers.

Written by Vijay

Python Developer | Backend Engineer | FastAPI | Flask | AWS | REST APIs | Scalable Microservices

Responses (4)

Write a response