🧱 Python Object-Oriented Programming (OOP)
Estimated reading: 3 minutes 93 views

🎯 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

MistakeWhy It’s a ProblemFix
Using plain strings for statesLeads to typos and inconsistencyUse Enums
Comparing enum to string directlyEnum != "VALUE" unless using StrEnumUse Enum.value or StrEnum
Creating duplicate values without careCan cause logical errorsUse @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 constantsScattering constants across code
Prefer StrEnum/IntEnum when neededComparing enum with incompatible types
Name Enums with PascalCaseUsing lowercase enum class names
Use @unique for validationAllowing 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 with for
  • βœ… Use IntEnum for 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?

TypeCompatible withUse Case
Enumenum members onlygeneral-purpose enumerations
IntEnumintegerscomparisons, sorting, numeric ops
StrEnumstrings (Py 3.11+)APIs, configs, serialization

Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Python Enums

Or Copy Link

CONTENTS
Scroll to Top