Some text some message..
Back 🎨 Python Enum Class & Its Role in Validation 20 Aug, 2025

🌈 What is 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".


🌟 Why Use 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 Validation

Validation 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


🎯 Real-Life Use Cases

  1. User roles (Admin, Editor, Viewer) 👤

  2. Order status (Pending, Shipped, Delivered, Cancelled) 📦

  3. Payment methods (Credit, Debit, UPI, Wallet) 💳

  4. Days of the week (Mon–Sun) 📅

Enums ensure only valid options are accepted.


💡 Pro Tip

Instead of comparing strings, always compare Enums directly:

if role == UserRole.ADMIN:
    print("Full access granted")

This is cleaner, safer, and faster 🚀.


🎨 Summary

🔹 Enum = Named constants (like traffic lights 🚦).
🔹 Prevents invalid input & typos.
🔹 Perfect for validation of roles, states, options.
🔹 Makes code readable, reliable, and maintainable.