Sub topic 5
Letting Python choose values with auto()
This chapter assumes you can define a basic Enum, read .name and .value, and iterate over members. It also assumes you know how class bodies run and what a decorator does. Here you will learn how auto() picks member values, how it behaves with mixed enum types, and how to replace its default rule. You will also see why auto-generated numbers are risky to store.
Why auto() exists
Many enums only need distinct members, and the actual values don't matter. Writing 1, 2, 3 by hand has two costs. You can mistype a number and silently create an alias, as the earlier chapter on aliases showed. You also have to renumber when you insert a member in the middle.
enum.auto() asks Python to choose each value for you.
from enum import Enum, auto
class Direction(Enum):
NORTH = auto()
EAST = auto()
SOUTH = auto()
WEST = auto()
print(list(Direction))
print(Direction.SOUTH.value)The output is:
[<Direction.NORTH: 1>, <Direction.EAST: 2>, <Direction.SOUTH: 3>, <Direction.WEST: 4>]
3By default, the first member gets 1, and each later auto() gets the next integer.
What auto() really is
auto() is not a number. Each call creates a small placeholder object. While the class body runs, Python's enum machinery sees the placeholder and replaces it with a real value, which it gets by calling a hook named _generate_next_value_.
This has a practical consequence. Inside the class body, NORTH is still a placeholder, so you cannot use it in arithmetic or compare it to anything. After the class is created, Direction.NORTH.value is a plain int.
The default rule
The hook receives four arguments.
| Argument | Meaning |
|---|---|
| `name` | The member name, such as `"NORTH"` |
| `start` | The first number to use, `1` by default |
| `count` | How many members have been defined so far |
| `last_values` | A list of the values of earlier members |
The default implementation for a plain Enum takes the last numeric value and adds one. If there are no earlier values, it returns start.
This explains what happens when you mix explicit values and auto(). The counter continues from the previous value, not from zero.
from enum import IntEnum, auto
class Severity(IntEnum):
LOW = 10
MEDIUM = auto()
HIGH = auto()
CRITICAL = 50
FATAL = auto()
print([(s.name, s.value) for s in Severity])The output is:
[('LOW', 10), ('MEDIUM', 11), ('HIGH', 12), ('CRITICAL', 50), ('FATAL', 51)]Only the numeric value that comes just before each auto() matters, so you can reset the sequence at any point by writing an explicit number.
Mixing auto() with non-integer values
If an earlier value is not a number, the default rule cannot add one to it. Depending on your Python version, you get a TypeError or a deprecation warning. If you need to mix types, either give every member an explicit value or define your own _generate_next_value_, as shown below.
auto() in StrEnum, IntEnum and Flag
The mixin and flag classes override the default rule, so auto() gives different results depending on the base class.
from enum import Flag, IntEnum, StrEnum, auto # StrEnum requires Python 3.11+
class Rank(IntEnum):
BRONZE = auto()
SILVER = auto()
GOLD = auto()
class Mode(StrEnum):
READ = auto()
WRITE = auto()
class Perm(Flag):
READ = auto()
WRITE = auto()
EXECUTE = auto()
print(Rank.GOLD.value)
print(Mode.WRITE.value)
print([p.value for p in Perm])The output is:
3
write
[1, 2, 4]IntEnumuses the ordinary counting rule.StrEnumuses the lowercased member name.Mode.READ.valueis"read", not"READ".FlagandIntFlaguse the next power of two (1, 2, 4, 8, and so on), so every member occupies its own bit and members can be combined with|.
The Flag behavior is the reason auto() matters most for flags. Computing 1 << 5 by hand is easy to get wrong. auto() never does.
Writing your own _generate_next_value_
You can change the rule by defining _generate_next_value_ in the class body. Two requirements apply. It must be defined before any member that uses auto(). It is also called on the class machinery directly, so it takes name first and has no self or cls.
A common use is making each value equal to the member's name.
from enum import Enum, auto
class Env(Enum):
def _generate_next_value_(name, start, count, last_values):
return name.lower()
DEV = auto()
STAGING = auto()
PROD = auto()
print([e.value for e in Env])
print(Env("prod"))The output is:
['dev', 'staging', 'prod']
Env.PRODTo reuse the rule across several enums, put it in a base class that has no members. Python allows subclassing an enum only when it defines no members, so this is legal.
from enum import Enum, auto
class AutoName(Enum):
def _generate_next_value_(name, start, count, last_values):
return name
class Fruit(AutoName):
APPLE = auto()
PEAR = auto()
print(Fruit.PEAR.value)The output is PEAR.
The hook can use last_values and count too. This version produces powers of ten.
from enum import IntEnum, auto
class Scale(IntEnum):
def _generate_next_value_(name, start, count, last_values):
return 10 ** count
ONES = auto()
TENS = auto()
HUNDREDS = auto()
print([s.value for s in Scale])The output is [1, 10, 100]. Here count is 0 for the first member, so the first value is 10 ** 0.
Edge cases
auto() as the whole value
Use auto() as the entire right-hand side. A form like auto() + 1 does not work, because auto() is a placeholder object, not a number. If you need a computed value, write a custom _generate_next_value_.
auto() cannot create an alias by itself
Each call to the default rule produces a new value, so auto() never creates an alias. Aliases appear only when you assign an existing value, or return a repeated value from a custom hook.
from enum import Enum, auto
class Shape(Enum):
def _generate_next_value_(name, start, count, last_values):
return "shape" # every member gets the same value
CIRCLE = auto()
SQUARE = auto()
print(Shape.SQUARE is Shape.CIRCLE)
print(list(Shape))The output is:
True
[<Shape.CIRCLE: 'shape'>]SQUARE becomes an alias for CIRCLE. Adding @unique to this class would raise ValueError at definition time, so the two features work well together.
Methods and private names are not members
Only plain assignments in the class body become members. Functions, properties, and names written like _ignored_ or __private do not. Writing helper = auto() makes a member called helper. Don't use auto() for anything you don't want treated as a member.
The main pitfall: auto values are positional
Values from auto() depend on definition order. Inserting or reordering members changes the numbers of every member after the change.
from enum import Enum, auto
class StatusV1(Enum):
NEW = auto()
DONE = auto()
class StatusV2(Enum):
NEW = auto()
IN_PROGRESS = auto() # inserted in the middle
DONE = auto()
print(StatusV1.DONE.value, StatusV2.DONE.value)The output is 2 3.
If you saved 2 in a database, a file, or an API response under StatusV1, that stored 2 now means IN_PROGRESS after the change. The code still runs. The data is silently wrong.
Choosing between auto() and explicit values
| Situation | Choice |
|---|---|
| Members only need to be distinct, and values stay inside your program | `auto()` |
| Bit flags | `auto()` with `Flag` or `IntFlag` |
| Values are saved, sent over a network, or shown to users | Explicit values |
| The text value should match the member name | `StrEnum` with `auto()`, or a custom hook |
| Values must match an external specification, such as HTTP codes | Explicit values |
Exercise
Given the class below, what are the values of A, B, C and D? from enum import IntEnum, auto class Level(IntEnum): A = auto() B = 5 C = auto() D = auto()
Show answer
A is 1, because it is the first member and the default start is 1. B is 5, which was set explicitly. C is 6 and D is 7, because each auto() continues from the previous value.
Exercise
A class defines class Mode(StrEnum) with READ = auto() and WRITE = auto(). What is Mode.WRITE.value, and why would an Enum with the same members give a different result?
Show answer
Mode.WRITE.value is "write". StrEnum's rule returns the lowercased member name. A plain Enum uses the default counting rule, so its WRITE member would have the integer value 2.