Skip to content
Foxipa

Suggest an edit

Tell us what should be corrected, clarified, or improved. Submission will be connected to Foxipa’s contribution service later.

No information is sent anywhere yet. Your suggestion is only prepared in your browser.

Learning

Python Enumerations with enum.Enum

Learn how to model a fixed set of named choices with Enum, inspect member names and values, look up and iterate over members, and prevent accidental aliases.

Levels: Intermediate ~15 min read

Intermediate

An enumeration (usually called an enum) gives a fixed set of symbolic member names to a type of value. It is useful when a variable should represent one of a known set of choices, such as an order state, direction, or user role. Instead of repeating loosely related strings or numbers, you define the allowed choices once.

Use an enum for a fixed set of choices

Subclass enum.Enum to define a set of named members. Each member is accessed through the enumeration class, making the allowed choices visible in code and discoverable by readers and tools.

Interactive Runnable example
Edit

Ready to run.

JobState.RUNNING is an enum member. Its name is RUNNING and its value is the string 'running'. The member itself is a named object; the value is the data associated with it.

A member has a name and a value

Use .name when you need the member's declared name and .value when you need its associated value. Plain Enum members do not automatically compare equal to their raw values, so JobState.RUNNING == 'running' is false. Compare members with members when your code is working with the enum itself.

Interactive Runnable example
Edit

Ready to run.

Quick check

What does Priority.HIGH.value return in the example?

from enum import Enum

class Priority(Enum):
    LOW = 1
    NORMAL = 2
    HIGH = 3

print(Priority.HIGH.value)

Look up a member by name or by value

Use square-bracket lookup with the declared name, such as JobState['RUNNING']. Call the enum class with a value, such as JobState('running'), to retrieve the corresponding member. The lookup forms answer different questions: names are identifiers in the class, while values are the data assigned to members.

Interactive Runnable example
Edit

Ready to run.

A missing name raises KeyError, and a value not assigned to any member raises ValueError. If values come from user input or a file, handle the relevant error at that input boundary instead of assuming every value is valid.

Interactive Runnable example
Edit

Ready to run.

Quick check

Which expression looks up an enum member by its assigned value?

from enum import Enum

class Color(Enum):
    RED = "red"
    BLUE = "blue"

print(Color("red"))

Iterate over the declared members

Iterating over an enum yields its canonical members in definition order. This is useful when you need to populate a menu, display available states, or process every declared choice. It does not mean arbitrary external values are automatically accepted.

Interactive Runnable example
Edit

Ready to run.

Quick check

In what order does iterating over an enum yield its canonical members?

from enum import Enum

class Plan(Enum):
    BASIC = "basic"
    PRO = "pro"
    TEAM = "team"

print([item.name for item in Plan])

Use auto() and guard against accidental aliases

enum.auto() asks Enum to generate a value when the particular value is not important. For a plain Enum, the default sequence starts at 1 and increases. If the value is part of a file format, API, or database contract, prefer explicit values whose meaning should remain stable.

Interactive Runnable example
Edit

Ready to run.

Two names with the same value become aliases for the same member. Aliases can be intentional, but accidental duplicates can hide mistakes. The @unique decorator rejects duplicate values when the enum class is created.

Interactive Runnable example
Edit

Ready to run.

Quick check

What does @unique do when two enum names have the same value?

from enum import Enum, unique

try:
    @unique
    class Status(Enum):
        READY = 1
        PREPARED = 1
except ValueError as error:
    print(type(error).__name__)

Quick check

Why might explicit enum values be preferable to auto() for a public protocol?

from enum import Enum

class FileKind(Enum):
    TEXT = "text/plain"
    JSON = "application/json"

print(FileKind.JSON.value)

Key takeaways

  • Use Enum to name a finite set of allowed choices.
  • Distinguish a member's .name from its .value.
  • Use square brackets for name lookup and call syntax for value lookup.
  • Iteration follows definition order and returns canonical members.
  • Use auto() for convenient generated values and @unique to reject accidental duplicate values.
Was this page helpful?

Mark this learning resource complete to track your learning progress.