Sub topic 2
Letting Python Choose Enum Values with `auto()`
Assume you know Python classes, decorators, functions, and the difference between == and is. This chapter uses those ideas to add behavior to enum members.
Automatic values with `auto()`
auto() asks Enum to generate a value. For a normal enum, values start at 1 and increase by one.
from enum import Enum, auto
class Direction(Enum):
NORTH = auto()
EAST = auto()
SOUTH = auto()
WEST = auto()
print(Direction.SOUTH.value) # 3Use auto() when the actual numbers do not matter. If the numbers are part of a public file format or database contract, explicit values are usually safer.
Comparing members and using them as keys
Enum members are singleton objects. A member defined once is reused everywhere, so identity and equality both work for the same member.
A plain Enum member does not equal its raw value:
| Expression | Result |
|---|---|
| `Direction.NORTH == Direction.NORTH` | `True` |
| `Direction.NORTH is Direction.NORTH` | `True` |
| `Direction.NORTH == 1` | `False` |
Members are hashable, so they can be dictionary keys or set elements.
labels = {
Direction.NORTH: "up",
Direction.SOUTH: "down",
}
print(labels[Direction.NORTH]) # upAn invalid value lookup, such as Direction(99), raises ValueError.
Adding methods, properties, and fields
An enum class can contain methods and properties. Tuple values can be unpacked into fields by __init__.
from enum import Enum
class Planet(Enum):
EARTH = (5.976e24, 6.37814e6)
def __init__(self, mass, radius):
self.mass = mass
self.radius = radius
@property
def surface_gravity(self):
return 6.673e-11 * self.mass / self.radius**2
print(round(Planet.EARTH.surface_gravity, 1)) # 9.8Type hints, dictionaries, and `match`
Use the enum class in a type hint to document the allowed values. A match statement can dispatch on specific members.
from enum import Enum
class Command(Enum):
START = "start"
STOP = "stop"
def handle(command: Command) -> str:
match command:
case Command.START:
return "starting"
case Command.STOP:
return "stopping"
print(handle(Command("stop"))) # stoppingExercise
What does Color(2) return if Color.GREEN = 2?
Show answer
It returns Color.GREEN, the enum member whose value is 2.