Member-only story
Guide to Python Enums I never had before
Hands-on guide on using Python Enums
Introduction
Have you ever found yourself using magic strings or integers in your Python code and wishing there was a better way? Enter Python Enums — your new best friend for creating sets of named constants. This guide will walk you through everything you need to know about Enums in Python, from the basics to some advanced tricks.
What are Enums?
Enums, short for “enumerations”, are a way to create a set of named constants. They help make your code more readable, maintainable, and less error-prone.
Basic Usage
Let’s start with a simple example:
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
print(Color.RED) # Output: Color.RED
print(Color.RED.name) # Output: RED
print(Color.RED.value) # Output: 1
In this example, we’ve created an Enum called `Color` with three members: RED, GREEN, and BLUE.
Why Use Enums?
1. Readability: Color. RED is much clearer than a magic number like `1`.
2. Type Safety: You can’t accidentally assign an invalid colour.
3. Iteration: You can easily iterate over all possible values.