Content · Programming · Python

Python enum.Enum: Create Named Constants

Model a fixed group of named choices with enum.Enum.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Model a fixed group of named choices with enum.Enum.

What You Will Learn


Enum members have stable names and values, and the member is typically compared by identity. Enums make states explicit while preventing arbitrary ad hoc string values from silently joining the set.

Use enum.StrEnum when direct string behavior is important.

Class interfaces should preserve their stated invariants. Type annotations describe intent but do not enforce runtime types on their own.

Step-by-Step Example


The example below makes the behavior visible with small input values that you can change safely.

from enum import Enum

class OrderStatus(Enum):
    NEW = "new"
    SHIPPED = "shipped"

current_status = OrderStatus.NEW
print(current_status.name)
print(current_status.value)
print(current_status is OrderStatus.NEW)

How the Example Works


  • The imports provide the standard-library tools used in the demonstration: enum.
  • The class OrderStatus groups data and behavior; its methods run when called on an instance.
  • The variable current_status holds the result of OrderStatus.NEW. Later lines use that value or inspect how it changes.
  • The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.

Expected output from the example:

NEW
new
True

When You Would Use This


A class becomes useful when several operations must maintain rules around related data. Think about which state belongs to each instance, which operations should be public, and how errors should be reported. Avoid making the design more complex than the underlying task.

Practice: Modify the Code


Create an Enum for three support-ticket states.

Verify the changed output against the behavior described above, including the relevant invalid or boundary case.

For complete parameters and version details, consult the official Python documentation.

Common Beginner Mistakes


  • Comparing a plain string directly to an Enum member instead of using its .value.
  • Expecting to add new members to an existing Enum dynamically at runtime.

Key Takeaways


  • Model a fixed group of named choices with enum.Enum.
  • Enum members have stable names and values, and the member is typically compared by identity.
  • Use enum.StrEnum when direct string behavior is important.
Share this resourceSend this page to someone who may find it useful.