π― Python Enum, IntEnum, StrEnum β Guide with Examples
π§² Introduction β Why Use Enums in Python?
In many applications, you need a set of named constant valuesβfor example, days of the week, status codes, or user roles.
Instead of using plain strings or integers, Python’s enum module helps you:
- Define human-readable constant values
- Ensure uniqueness and safety
- Group related values under one class
π― In this guide, you’ll learn:
- What Enums are and how they work
- How to create and access Enum members
- Enum types:
Enum,IntEnum,StrEnum - Best practices and common pitfalls
β What Is an Enum?
An Enum (Enumeration) is a class that contains a set of constant members, each with a unique name and value.
Enums improve readability, safety, and code structure.
π§ How to Define a Python Enum
β€ Import Enum from the enum module:
from enum import Enum
class Status(Enum):
PENDING = 1
APPROVED = 2
REJECTED = 3
β Accessing Enum Members
print(Status.PENDING) # Status.PENDING
print(Status.PENDING.name) # PENDING
print(Status.PENDING.value) # 1
π‘ Enums are class members with unique name and value.
π§ͺ Iterating Over Enum Members
for status in Status:
print(status.name, status.value)
β Output:
PENDING 1
APPROVED 2
REJECTED 3
π Comparison and Identity
if Status.APPROVED == Status(2):
print("Approved!")
π‘ You can compare enums by value or by identity (is keyword).
π’ Using IntEnum (Supports Integer Comparison)
from enum import IntEnum
class Priority(IntEnum):
LOW = 1
MEDIUM = 2
HIGH = 3
print(Priority.HIGH > Priority.LOW) # β
True
β
IntEnum members are compatible with integers in comparisons.
π Python 3.11+: StrEnum for String Comparison
from enum import StrEnum
class Color(StrEnum):
RED = "red"
GREEN = "green"
BLUE = "blue"
print(Color.RED == "red") # β
True
π‘ Great when working with APIs or string-based configs.
π¦ Real-World Example β User Roles
from enum import Enum
class Role(Enum):
ADMIN = "admin"
MODERATOR = "moderator"
USER = "user"
def has_permission(role):
if role == Role.ADMIN:
return True
return False
print(has_permission(Role.ADMIN)) # True
print(has_permission(Role.USER)) # False
β Common Pitfalls with Enums
| Mistake | Why Itβs a Problem | Fix |
|---|---|---|
| Using plain strings for states | Leads to typos and inconsistency | Use Enums |
| Comparing enum to string directly | Enum != "VALUE" unless using StrEnum | Use Enum.value or StrEnum |
| Creating duplicate values without care | Can cause logical errors | Use @unique decorator |
π§Ό Enforcing Unique Values with @unique
from enum import Enum, unique
@unique
class Status(Enum):
ACTIVE = 1
INACTIVE = 2
# ACTIVE = 2 β would raise ValueError
β Ensures no duplicate values in your Enum.
π Best Practices
| β Do This | β Avoid This |
|---|---|
| Use Enums for related constants | Scattering constants across code |
Prefer StrEnum/IntEnum when needed | Comparing enum with incompatible types |
| Name Enums with PascalCase | Using lowercase enum class names |
Use @unique for validation | Allowing silent duplicates |
π Summary β Recap & Next Steps
Enums in Python provide a structured, readable, and type-safe way to manage constants. They are a great replacement for primitive values in status codes, roles, and configuration flags.
π Key Takeaways:
- β Use Enums to define named constants
- β
Access with
.name,.value, and loop withfor - β
Use
IntEnumfor numeric comparison - β
Use
StrEnum(Python 3.11+) for string matching - β
Validate uniqueness with
@unique
βοΈ Real-World Relevance:
Used in web apps, database status codes, API response types, and config-driven applications.
β FAQ β Python Enums
β What is an Enum in Python?
β A class that defines a set of named constant values, grouped together under a common namespace.
β Can I compare an Enum to a string or int?
β
Only if youβre using StrEnum or IntEnum. Otherwise, compare using .value.
β Can I have duplicate values in an Enum?
β οΈ Yes by default, but you can prevent this using @unique.
β Can I iterate over enum members?
β Yes:
for item in EnumClass:
print(item.name, item.value)
β What’s the difference between Enum, IntEnum, and StrEnum?
| Type | Compatible with | Use Case |
|---|---|---|
Enum | enum members only | general-purpose enumerations |
IntEnum | integers | comparisons, sorting, numeric ops |
StrEnum | strings (Py 3.11+) | APIs, configs, serialization |
Share Now :
