Python enum Module - A Complete Guide

In this guide, you'll explore Python's enum module, which is used to create enumerations. Learn its features and examples to define symbolic names for values.

The enum module in Python provides support for creating enumerations, which are a set of symbolic names bound to unique, constant values. Enumerations are useful for representing fixed sets of related values, such as days of the week, states, directions, etc.

Table of Contents

  1. Introduction
  2. Enum Types
    • EnumType
    • Enum
    • IntEnum
    • StrEnum
    • Flag
    • IntFlag
    • ReprEnum
    • EnumCheck
    • FlagBoundary
  3. Key Functions and Decorators
    • auto
    • property
    • unique
    • verify
    • member
    • nonmember
    • global_enum
    • show_flag_values
  4. Creating Enumerations
    • Basic Enum
    • Auto-Generating Values
    • Customizing Enum Members
  5. Enum Methods and Properties
  6. Iteration and Comparison
  7. Advanced Enum Features
    • Using Decorators
    • Custom Methods
  8. Examples
    • Enum with Explicit Values
    • Enum with Auto-Generated Values
    • Custom Enum Methods
  9. Real-World Use Case
  10. Conclusion
  11. References

Introduction

Enumerations, or Enums, provide a way to define a set of named values. These values are constants and can be used to represent fixed categories or states in your program. Enums enhance code readability and maintainability by providing meaningful names instead of arbitrary numeric or string values.

Enum Types

EnumType

EnumType is the metaclass for Enum and its subclasses. It handles the creation of new enumeration types.

Enum

The base class for creating enumerated constants. Members of an Enum class are constants.

from enum import Enum

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

print(Color.RED)
print(Color.GREEN.value)

Output:

Color.RED
2

IntEnum

A variation of Enum where members are also subclasses of int. This means they can be compared to integers and other IntEnum members.

from enum import IntEnum

class Priority(IntEnum):
    LOW = 1
    MEDIUM = 2
    HIGH = 3

print(Priority.LOW)
print(Priority.LOW == 1)

Output:

1
True

StrEnum

A variation of Enum where members are also subclasses of str. This means they can be compared to strings and other StrEnum members.

from enum import StrEnum

class Status(StrEnum):
    ACTIVE = 'active'
    INACTIVE = 'inactive'
    PENDING = 'pending'

print(Status.ACTIVE)
print(Status.ACTIVE == 'active')

Output:

active
True

Flag

A base class for creating enumerated constants that can be combined using bitwise operations without losing their Flag membership.

from enum import Flag, auto

class Permission(Flag):
    READ = auto()
    WRITE = auto()
    EXECUTE = auto()

perm = Permission.READ | Permission.WRITE
print(perm)
print(Permission.READ in perm)

Output:

Permission.READ|WRITE
True

IntFlag

A base class for creating enumerated constants that can be combined using bitwise operators without losing their IntFlag membership. IntFlag members are also subclasses of int.

from enum import IntFlag, auto

class Permission(IntFlag):
    READ = auto()
    WRITE = auto()
    EXECUTE = auto()

perm = Permission.READ | Permission.WRITE
print(perm)
print(Permission.READ in perm)

Output:

3
True

ReprEnum

Used by IntEnum, StrEnum, and IntFlag to keep the str() of the mixed-in type.

EnumCheck

An enumeration with the values CONTINUOUS, NAMED_FLAGS, and UNIQUE, for use with verify() to ensure various constraints are met by a given enumeration.

FlagBoundary

An enumeration with the values STRICT, CONFORM, EJECT, and KEEP which allows for more fine-grained control over how invalid values are dealt with in an enumeration.

Key Functions and Decorators

auto

Instances are replaced with an appropriate value for Enum members. StrEnum defaults to the lower-cased version of the member name, while other Enums default to 1 and increase from there.

from enum import Enum, auto

class Color(Enum):
    RED = auto()
    GREEN = auto()
    BLUE = auto()

print(list(Color))

Output:

[<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 3>]

property

Allows Enum members to have attributes without conflicting with member names. The value and name attributes are implemented this way.

from enum import Enum, auto

class Color(Enum):
    RED = auto()
    GREEN = auto()
    BLUE = auto()

    @property
    def description(self):
        return self.name.lower()

print(Color.RED.description)

Output:

red

unique

Enum class decorator that ensures only one name is bound to any one value.

from enum import Enum, unique

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

verify

Enum class decorator that checks user-selectable constraints on an enumeration.

member

Make obj a member. Can be used as a decorator.

nonmember

Do not make obj a member. Can be used as a decorator.

global_enum

Modify the str() and repr() of an enum to show its members as belonging to the module instead of its class, and export the enum members to the global namespace.

show_flag_values

Return a list of all power-of-two integers contained in a flag.

Creating Enumerations

Basic Enum

To create an enumeration, you subclass the Enum class and define class attributes.

from enum import Enum

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

print(Color.RED)
print(Color.GREEN.value)

Output:

Color.RED
2

Auto-Generating Values

You can use the auto() function to automatically assign values to enum members.

from enum import Enum, auto

class Color(Enum):
    RED = auto()
    GREEN = auto()
    BLUE = auto()

print(list(Color))

Output:

[<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 3>]

Customizing Enum Members

You can define custom attributes and methods for enum members.

from enum import Enum

class Color(Enum):
    RED = (1, 'Red')
    GREEN = (2, 'Green')
    BLUE = (3, 'Blue')

    def __init__(self, num, description):
        self._value_ = num
        self.description = description

print(Color.RED.description)  # Outputs: Red
print(Color.GREEN.value)      # Outputs: 2

Output:

Red
2

Enum Methods and Properties

Enums provide several useful methods and properties.

  • name: Returns the name of the enum member.
  • value: Returns the value of the enum member.
  • Enum.__members__: A dictionary of all members in the enumeration.
from enum import Enum

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

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

Output:

RED
2
{'RED': <Color.RED: 1>, 'GREEN': <Color.GREEN: 2>, 'BLUE': <Color.BLUE: 3>}

Iteration and Comparison

You can iterate over enum members and compare them using their names or values.

from enum import Enum

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

for color in Color:
    print(color)

print(Color.RED == Color.RED)
print(Color.RED == Color.GREEN)

Output:

Color.RED
Color.GREEN
Color.BLUE
True
False

Advanced Enum Features

Using Decorators

The unique decorator ensures that there are no duplicate values in the enumeration.

from enum import Enum, unique

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

Custom Methods

Enums can have custom methods to add functionality.

from enum import Enum

class Direction(Enum):
    NORTH = 1
    EAST = 2
    SOUTH = 3
    WEST = 4

    def is_opposite(self, other):
        opposites = {Direction.NORTH: Direction.SOUTH,
                     Direction.SOUTH: Direction.NORTH,
                     Direction.EAST: Direction.WEST,
                     Direction.WEST: Direction.EAST}
        return opposites[self] == other

print(Direction.NORTH.is_opposite(Direction.SOUTH))
print(Direction.EAST.is_opposite(Direction.WEST))
print(Direction.NORTH.is_opposite(Direction.EAST))

Output:

True
True
False

Examples

Enum with Explicit Values

Define an enum with explicit values.

from enum import Enum

class Status(Enum):
    PENDING = 1
    IN_PROGRESS = 2
    COMPLETED = 3

print(Status.PENDING)
print(Status.COMPLETED.value)

Output:

Status.PENDING
3

Enum with Auto-Generated Values

Define an enum with auto-generated values using auto().

from enum import Enum, auto

class Status(Enum):
    PENDING = auto()
    IN_PROGRESS = auto()
    COMPLETED = auto()

print(Status.PENDING.value)
print(Status.COMPLETED.value)

Output:

1
3

Custom Enum Methods

Define an enum with custom methods.

from enum import Enum

class Direction(Enum):
    NORTH = 1
    EAST = 2
    SOUTH = 3
    WEST = 4

    def is_opposite(self, other):
        opposites = {Direction.NORTH: Direction.SOUTH,
                     Direction.SOUTH: Direction.NORTH,
                     Direction.EAST: Direction.WEST,
                     Direction.WEST: Direction.EAST}
        return opposites[self] == other

print(Direction.NORTH.is_opposite(Direction.SOUTH))
print(Direction.EAST.is_opposite(Direction.WEST))
print(Direction.NORTH.is_opposite(Direction.EAST))

Output:

True
True
False

Real-World Use Case

State Machine

Enums are often used in state machines to represent different states.

from enum import Enum, auto

class State(Enum):
    IDLE = auto()
    RUNNING = auto()
    PAUSED = auto()
    STOPPED = auto()

class StateMachine:
    def __init__(self):
        self.state = State.IDLE

    def change_state(self, new_state):
        if isinstance(new_state, State):
            self.state = new_state
            print(f"State changed to {self.state.name}")
        else:
            raise ValueError("Invalid state")

sm = StateMachine()
sm.change_state(State.RUNNING)
sm.change_state(State.PAUSED)
sm.change_state(State.STOPPED)

Output:

State changed to RUNNING
State changed to PAUSED
State changed to STOPPED

Conclusion

The enum module in Python provides a robust way to define and manage sets of related constants. By using enums, you can improve the readability and maintainability of your code, especially when dealing with fixed categories or states. Enums can be customized with additional attributes and methods, making them versatile for a variety of applications.

References

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare