Header Ads Widget

⚡ Premium Tools Hub • EXE Apps + Full Python Source Code
Lite • Pro • Bundle Packs • Instant Download

Python Enums (Complete Guide for Beginners)

In Python, Enums (Enumeration) are used to define a set of named constant values. They make your code more readable, safer, and easier to maintain compared to using raw numbers or strings.


🔹 What is an Enum in Python?

An Enum is:

A collection of symbolic names (members) bound to unique constant values.

In simple terms:

  • Instead of using random numbers or strings
  • You use meaningful names for fixed values

🔹 Why Use Enums?

Enums help you:

  • ✔ Improve code readability
  • ✔ Avoid magic numbers (like 1, 2, 3 without meaning)
  • ✔ Prevent invalid values
  • ✔ Make code easier to maintain
  • ✔ Improve debugging and structure

🔹 Importing Enum in Python

Python provides a built-in module:

from enum import Enum

🔹 Creating an Enum Class

Basic Syntax:

from enum import Enum

class ClassName(Enum):
MEMBER1 = value1
MEMBER2 = value2

🔹 Simple Example of Enum

from enum import Enum

class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3

Accessing Enum Values:

print(Color.RED)
print(Color.RED.name)
print(Color.RED.value)

Output:

Color.RED
RED
1

🔹 Looping Through Enum

for color in Color:
print(color)

Output:

Color.RED
Color.GREEN
Color.BLUE

🔹 Enum with String Values

from enum import Enum

class Status(Enum):
PENDING = "pending"
SUCCESS = "success"
FAILED = "failed"

Usage:

print(Status.SUCCESS.value)

Output:

success

🔹 Real-Life Example of Enum

Order Status System

from enum import Enum

class OrderStatus(Enum):
PLACED = 1
SHIPPED = 2
DELIVERED = 3
CANCELLED = 4

Usage:

status = OrderStatus.SHIPPED

if status == OrderStatus.SHIPPED:
print("Your order is on the way")

Output:

Your order is on the way

🔹 Enum with Conditions

def check_status(status):
if status == OrderStatus.DELIVERED:
return "Order completed"
elif status == OrderStatus.CANCELLED:
return "Order cancelled"
else:
return "Order in progress"

Usage:

print(check_status(OrderStatus.PLACED))

🔹 Unique Feature of Enum

Enums are immutable, meaning:

✔ You cannot change their values accidentally

Color.RED = 10  # ❌ Error

🔹 Enum vs Normal Variables

FeatureEnumNormal Variables
ReadabilityHighLow
SafetyHighLow
StructureStrongWeak
ErrorsPrevents invalid valuesNo protection

🔹 Enum with Auto Values

Python can automatically assign values using auto():

from enum import Enum, auto

class Direction(Enum):
NORTH = auto()
SOUTH = auto()
EAST = auto()
WEST = auto()

Usage:

for d in Direction:
print(d.name, d.value)

🔹 Real-World Example (User Roles)

from enum import Enum

class Role(Enum):
ADMIN = "admin"
USER = "user"
GUEST = "guest"

Usage:

def access_level(role):
if role == Role.ADMIN:
return "Full access"
elif role == Role.USER:
return "Limited access"
else:
return "Read-only access"

🔹 Output Example:

Full access

🔹 Benefits of Enums

✅ 1. Better code readability

You use meaningful names instead of numbers.

✅ 2. Prevents errors

Only allowed values can be used.

✅ 3. Easy maintenance

Changes are centralized.

✅ 4. Improves structure

Makes code more professional and clean.


🔹 Common Mistakes

❌ Using raw strings instead of Enum

status = "shipped"  # not safe

❌ Trying to modify Enum values

OrderStatus.PLACED = 10  # ❌ Error

🔹 When to Use Enums?

Use Enums when:

  • You have fixed categories
  • You define states (order status, user roles)
  • You want safer code
  • You want better readability

🚀 Conclusion

Python Enums are a powerful way to define constant values with meaning. They make your code:

  • More readable
  • More structured
  • Less error-prone

They are widely used in:

  • Web applications
  • APIs
  • Game development
  • System design

 




Post a Comment

0 Comments