0
0
PythonHow-ToBeginner · 3 min read

How to Use Enum in Python: Syntax and Examples

In Python, use enum.Enum to create enumerations, which are sets of symbolic names bound to unique constant values. Define an enum by subclassing Enum and listing members as class attributes. Access enum members by name or value for clear, readable code.
📐

Syntax

To create an enum in Python, import Enum from the enum module, then define a class that inherits from Enum. Inside the class, define members as class attributes with constant values.

  • Enum class: The base class to create enumerations.
  • Members: Named constants inside the enum class.
  • Access: Use EnumName.MemberName or EnumName(value).
python
from enum import Enum

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

Example

This example shows how to define an enum for colors, access members by name and value, and print their names and values.

python
from enum import Enum

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

# Access by member name
print(Color.RED)          # Output: Color.RED
print(Color.RED.name)     # Output: RED
print(Color.RED.value)    # Output: 1

# Access by value
print(Color(2))           # Output: Color.GREEN

# Iterate over members
for color in Color:
    print(f'{color.name} = {color.value}')
Output
Color.RED RED 1 Color.GREEN RED = 1 GREEN = 2 BLUE = 3
⚠️

Common Pitfalls

Common mistakes when using enums include:

  • Trying to assign duplicate values without using @unique decorator or understanding value aliasing.
  • Comparing enum members to raw values instead of enum members.
  • Modifying enum members after creation (enums are immutable).

Always compare enum members directly, not their values.

python
from enum import Enum

class Status(Enum):
    SUCCESS = 1
    FAILURE = 1  # This creates an alias, not a new member

# Wrong comparison
if Status.SUCCESS == 1:
    print('Wrong: comparing enum member to int')

# Correct comparison
if Status.SUCCESS == Status.FAILURE:
    print('Correct: comparing enum members')
Output
Wrong: comparing enum member to int Correct: comparing enum members
📊

Quick Reference

ConceptDescription
Enum creationSubclass Enum and define members as class attributes
Access memberEnumName.MemberName or EnumName(value)
Get namemember.name returns the member's name as string
Get valuemember.value returns the member's value
IterationUse for member in EnumName to loop all members
UniquenessUse @unique decorator to prevent duplicate values

Key Takeaways

Use the enum module and subclass Enum to create enumerations in Python.
Access enum members by name or value for clear and readable code.
Compare enum members directly, not their raw values, to avoid bugs.
Enum members are immutable and should not be changed after creation.
Use the @unique decorator to ensure all enum values are distinct.