Automatically assign member values with enum.auto().
What You Will Learn
enum.auto() delegates value generation to the Enum class’s _generate_next_value_ logic. Standard Enum, IntEnum, StrEnum, and Flag families may generate different styles of values.
Set explicit values whenever a public protocol or stored format depends on exact numbers.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
from enum import Enum, auto
class ProcessingState(Enum):
WAITING = auto()
RUNNING = auto()
DONE = auto()
print(ProcessingState.WAITING.name)
print(ProcessingState.WAITING.value)
How the Example Works
- The imports provide the standard-library tools used in the demonstration: enum.
- The class ProcessingState groups data and behavior; its methods run when called on an instance.
- 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:
WAITING
1
When You Would Use This
These tools are useful when composing small reusable functions, adapting callbacks, or eliminating repeated work. Pay attention to whether the operation returns a new object, updates state, or produces lazy results. Test a small success case and a boundary case before integrating it into an application.
Practice: Modify the Code
Create three states using auto() and inspect their values.
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
- Assuming auto() generates the same kind of values for StrEnum and IntFlag.
- Depending on auto-generated numeric values as durable external database identifiers without a versioning policy.
Key Takeaways
- Automatically assign member values with enum.auto().
- enum.auto() delegates value generation to the Enum class’s _generate_next_value_ logic.
- Set explicit values whenever a public protocol or stored format depends on exact numbers.