Enum
?🔹 Enum (Enumeration) is a way to define a set of named constant values in Python.
Instead of using random strings or integers, you use meaningful names.
from enum import Enum
class UserRole(Enum):
ADMIN = "admin"
EDITOR = "editor"
VIEWER = "viewer"
Here, UserRole.ADMIN
is more meaningful than "admin"
.
Enum
?Think of Enum
as a traffic light 🚦 for your code:
It prevents invalid values and enforces consistency.
Without Enum ❌ | With Enum ✅ |
---|---|
role = "admnn" | role = UserRole.ADMIN |
Typos go unnoticed 😓 | Errors caught early 🎯 |
No fixed set of choices | Fixed, controlled set of options |
Enum
in ValidationValidation means checking if input is valid.
Enums make it easy because they restrict allowed values.
def validate_role(role: str):
if role not in [r.value for r in UserRole]:
raise ValueError("Invalid role!")
return role
✔ If user passes "admin"
→ ✅ valid
❌ If user passes "admnn"
→ ❌ ValueError
User roles (Admin, Editor, Viewer) 👤
Order status (Pending, Shipped, Delivered, Cancelled) 📦
Payment methods (Credit, Debit, UPI, Wallet) 💳
Days of the week (Mon–Sun) 📅
Enums ensure only valid options are accepted.
Instead of comparing strings, always compare Enums directly:
if role == UserRole.ADMIN:
print("Full access granted")
This is cleaner, safer, and faster 🚀.
🔹 Enum
= Named constants (like traffic lights 🚦).
🔹 Prevents invalid input & typos.
🔹 Perfect for validation of roles, states, options.
🔹 Makes code readable, reliable, and maintainable.