Not a Medium member? Have free access to this story via this link.

Imagine you're building a simple food ordering system in Python. You've got a status code: if it's 1, the order gets processed. And if it's 2, it gets cancelled. So, your code might look like this:

if status == 1:
    print("Order has been processed!")
elif status == 2:
    print("Oops! Something went wrong. Order was cancelled.")

In the above code, it's unclear what the constants 1 and 2 actually mean unless you scroll up to find a comment or check the code's documentation.

The numbers 1 and 2 are called "magic numbers" (or "magic strings" if you're using text values like "SUCCESS" or "FAILURE").

These values are scattered, error-prone, and difficult to maintain. A single typo or mismatch can silently break the logic of your entire application.

This is where Python's enum module comes in to save the day. It helps you manage constant values in a way that is both safe and readable.

In this tutorial, we'll explore how using an enum can not only clean up your code but also make it more self-explanatory. Whether you're building a small app or a large system, this one Python tool can save you from headaches you didn't even know you had.

Let's get started!

What is Enum in Python?

The word "Enum" is short for Enumeration. It refers to a class from Python's built-in enum module that allows you to create safe groups of constant values.

Each member in an enum has a name and a value. You can compare them, loop through them, access them directly, and even customize them.

To start using the Enum class from enum module, you first need to import it:

from enum import Enum

You can now define your order status constants like this:

class Status(Enum):
    SUCCESS = 1
    FAILURE = 2

Anyone reading this can instantly understand what's going on in here. And better yet, your code becomes bulletproof against those typos or invalid values.

Let's rewrite our order status logic using our Status enum this time:

status = Status.SUCCESS

if status == Status.SUCCESS:
    print("Order has been processed!")
elif status == Status.FAILURE:
    print("Oops! Something went wrong. Order was cancelled.")

This approach is now cleaner, more readable, and much easier to maintain.

Looping Through Enum Members

Since enums in Python are iterable, you can loop through their members. This makes your code more dynamic. You no longer need to hard-code values manually.

For example, if we want to print all options in our Status enum, we would write:

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

Output

SUCCESS 1
FAILURE 2

This is especially helpful when you want to display all the available choices to a user, validate inputs, or debug what values your enum holds.

Comparing Enum Members

Enums in Python are singletons. This means each member is unique and only one instance of it exists. Because of this, you can safely use the identity operator (is) when comparing enum members.

Let's say we want to check if the order status is "SUCCESS" before processing it. Here's how we can do that:

if status is Status.SUCCESS:
    print("Order has been processed!")

Output

Order is processing!

Why use is here? Using is works perfectly here because Status.SUCCESS is a singleton. Python guarantees it's the exact same object every time you reference it.

Creating Custom Methods Inside Enums

You can even define methods inside an enum in Python. This allows you to bundle related behaviour directly with the values, keeping your code more organised.

Let's update our order status example to include a method that checks whether the order is still being processed:

class Status(Enum):
    SUCCESS = 1
    FAILURE = 2

def can_process(self):
    return self == Status.SUCCESS

Now, if our order is still processing, we can check its status like this:

status = Status.SUCCESS

if status.can_process():
    print("Processing order…")
else:
    print("Order is not being processed.")

Output

Processing order…

This keeps all the logic related to enum values in one place — inside the enum itself.

Using auto() to Auto-Assign Values to Enum Members

Let's say you're a lazy coder. Or just someone who finds typing = 1, = 2, …, a bit boring. Well, Python has a fix for you!

You can use the auto() function from the enum module to automatically assign values to your enum members. Here's how:

class Status(Enum):
    SUCCESS = auto()
    FAILURE = auto()

Now, Python will automatically assign unique values to each member starting from 1 (by default). This is especially handy when you don't care about the actual numbers.

If you want to check those auto-assigned values, you can just write:

print(Status.SUCCESS.value) # Output: 1

print(Status.FAILURE.value) # Output: 2

Don't Make This Enum Mistake: Comparing to Raw Values

A common mistake many developers make with enum is comparing raw values (like 1) instead of using the actual enum members.

Sure, you could write something like this:

if status == 1:
    print("Order has been processed!")

It works, but it completely defeats the purpose of using enums in Python. By doing this, you're back to relying on magic numbers.

The correct way is to compare using the enum members themselves like this:

if status == Status.SUCCESS:
    print("Order has been processed!")

Now, you know what the value represents, and Python will even raise an error if you try to use an invalid value — something raw numbers can't do.

Final Words

I believe Python enums don't always get the spotlight they deserve, but they're one of those powerful tools that can truly transform the way you write Python code.

If you've ever felt like your constants were getting out of hand or your if conditions were becoming unreadable, enums are your best friend.

And always remember,

"Code is read more often than it's written. Make yours read like a well-told story, not a mystery novel. And Python enums help you do just that."

A Note from the Author

If you found this story helpful in your tech journey, consider subscribing! By following me, you'll stay updated on my latest articles, which are filled with valuable tech insights.

Thank you for reading, and see you in the next story!