How can I represent an ‘Enum’ in Python?

To represent an Enum (enumeration) in Python, use the enum module from the standard library. Enums provide a structured way to define named constants, improving code readability and type safety. Below is a detailed guide with examples:

1. Basic Enum Definition

Define an Enum by subclassing Enum and listing members as class attributes.

from enum import Enum

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

# Usage
print(Color.RED)        # Output: Color.RED
print(Color.RED.name)   # Output: 'RED'
print(Color.RED.value)  # Output: 1

2. Auto-Assigned Values

Use auto() to automatically assign incremental values.

from enum import Enum, auto

class Priority(Enum):
    LOW = auto()    # Value: 1
    MEDIUM = auto() # Value: 2
    HIGH = auto()   # Value: 3

print(Priority.HIGH.value)  # Output: 3

3. Enums with String Values

Assign meaningful string values for clarity.

class HTTPMethod(Enum):
    GET = "GET"
    POST = "POST"
    PUT = "PUT"
    DELETE = "DELETE"

print(HTTPMethod.POST.value)  # Output: 'POST'

4. Unique Values

Enforce unique values with the @unique decorator.

from enum import Enum, unique

@unique
class Status(Enum):
    PENDING = 1
    RUNNING = 2
    COMPLETED = 3  # Duplicate values will raise an error.

5. Iterating Over Enums

Loop through all members of an Enum.

for color in Color:
    print(color.name, color.value)

# Output:
# RED 1
# GREEN 2
# BLUE 3

6. Lookup by Value or Name

Retrieve members by their value or name.

# By value
print(Color(1))      # Output: Color.RED

# By name
print(Color['RED'])  # Output: Color.RED

7. IntEnum for Integer Comparisons

Use IntEnum to treat members as integers.

from enum import IntEnum

class Day(IntEnum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3

print(Day.MONDAY == 1)  # Output: True

8. StrEnum (Python 3.11+)

Compare members directly to strings.

from enum import StrEnum

class LogLevel(StrEnum):
    DEBUG = "DEBUG"
    INFO = "INFO"
    ERROR = "ERROR"

print(LogLevel.DEBUG == "DEBUG")  # Output: True

9. Enums with Methods

Add custom methods to enums for additional functionality.

from enum import Enum

class Planet(Enum):
    MERCURY = (3.303e23, 2.4397e6)
    EARTH = (5.976e24, 6.378e6)

    def __init__(self, mass, radius):
        self.mass = mass    # in kg
        self.radius = radius  # in meters

    @property
    def gravity(self):
        G = 6.673e-11
        return G * self.mass / (self.radius ** 2)

print(Planet.EARTH.gravity)  # Output: ~9.798 m/s²

10. Enums in Practice

Use enums to validate function arguments.

def set_light(color: Color):
    if not isinstance(color, Color):
        raise ValueError("Invalid color")
    print(f"Light set to {color.name}")

set_light(Color.RED)  # Valid
set_light(1)          # Raises ValueError

Key Features

FeatureDescription
Named ConstantsImprove code readability by replacing magic numbers/strings.
Type SafetyEnforce valid values in function parameters.
Unique ValuesPrevent duplicates with @unique.
Methods/PropertiesAttach logic directly to enum members.
LookupRetrieve members by name or value.

When to Use Enums

  • Represent a fixed set of constants (e.g., states, error codes, options).
  • Replace ambiguous strings/integers with meaningful names.
  • Validate inputs in functions/APIs.

Summary

  1. Use Enum for general-purpose named constants.
  2. Use IntEnum/StrEnum for integer/string comparisons.
  3. Decorate with @unique to enforce unique values.
  4. Add methods to encapsulate member-specific logic.

Enums make your code more robust and self-documenting.

Leave a Reply

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