Sub topic 13
Customizing lookup and value generation
This chapter covers two hooks that change how an Enum class finds members and how it numbers them: _missing_ and _generate_next_value_. It assumes you know how Color(2) and Color["BLUE"] work, what auto() does, and how classmethods and staticmethods are defined. The examples were written for Python 3.11 and later.
Where the hooks fit
Both hooks are single-underscore names that the enum module calls for you. You never call them directly.
_missing_runs when a lookup by value fails._generate_next_value_runs each timeauto()needs a value.
Most enums need neither hook. They help when you accept messy input, such as user-typed text, or when you want values derived from member names.
Customizing failed lookups with `_missing_`
Calling the class with a value, as in Level("high"), searches the members for that value. If nothing matches, the class calls cls._missing_(value). The default implementation returns None, which produces the familiar ValueError.
You can override it as a classmethod. Return a member to make the lookup succeed. Return None to keep the normal ValueError.
from enum import Enum
class Level(Enum):
LOW = "low"
HIGH = "high"
@classmethod
def _missing_(cls, value):
if isinstance(value, str):
for member in cls:
if member.value == value.lower():
return member
return None
print(Level("HIGH")) # Level.HIGH
print(Level("low")) # Level.LOW (found directly, _missing_ not called)
try:
Level("medium")
except ValueError as exc:
print(exc) # 'medium' is not a valid Level
try:
Level(3)
except ValueError as exc:
print(exc) # 3 is not a valid LevelThe isinstance check matters. _missing_ receives whatever the caller passed, including None, integers, or lists. Without the check, Level(3) would fail with AttributeError: 'int' object has no attribute 'lower' instead of the clean ValueError.
The lookup flow
What `_missing_` does not cover
_missing_ is only part of value lookup. These operations never call it:
Level["HIGH"]looks up by name and raisesKeyErroron failure.Level.HIGHis plain attribute access and raisesAttributeErroron failure.- Comparisons such as
Level.HIGH == "high"are not lookups at all.
If you want case-insensitive name lookup, you need a separate classmethod, or you can define __class_getitem__-style behavior on a custom metaclass. A small parse classmethod is usually clearer.
Falling back to a default member
A common use is to map every unknown value to a sentinel member.
from enum import Enum
class Status(Enum):
ACTIVE = "active"
INACTIVE = "inactive"
UNKNOWN = "unknown"
@classmethod
def _missing_(cls, value):
return cls.UNKNOWN
print(Status("active")) # Status.ACTIVE
print(Status("suspended")) # Status.UNKNOWN
print(Status(42)) # Status.UNKNOWNThis is convenient when you read data from an external source that may add new values later. The cost is that typos stop raising errors. Status("activ") quietly becomes UNKNOWN. Use a fallback only when losing that error is acceptable, and log the original value if you can.
Errors inside `_missing_`
Three mistakes show up often:
- Returning the wrong type. If
_missing_returns something that is neitherNonenor an instance of the class, the lookup raisesTypeError. Returning the raw value, such asreturn value.lower(), is the usual cause. Return the member, not the cleaned-up value. - Infinite recursion. Calling
cls(cleaned_value)inside_missing_triggers another failed lookup whencleaned_valueis also invalid. That calls_missing_again, and so on, untilRecursionError. Search the members directly instead, as the loop above does. - Forgetting
@classmethod. Without it, the hook is called with the wrong arguments and fails with a confusingTypeErrorabout missing arguments.
Customizing `auto()` with `_generate_next_value_`
auto() is a placeholder. When the class body finishes a member assignment that uses it, the class calls _generate_next_value_ to get the real value. The default returns 1 for the first member and then the previous value plus one. Flag replaces the default with powers of two, and StrEnum replaces it with the lowercase member name.
The hook takes four arguments:
| Argument | Meaning |
|---|---|
| `name` | The member name being defined, such as `"NORTH"` |
| `start` | The starting number, `1` by default |
| `count` | How many members have been defined so far |
| `last_values` | A list of the values of earlier members, including ones you assigned explicitly |
Define it with @staticmethod, and define it before any member. Members defined earlier in the class body would already have received their values from the default.
Using the member name as the value
Putting the hook in a base class with no members lets several enums share it.
from enum import Enum, auto
class AutoName(Enum):
@staticmethod
def _generate_next_value_(name, start, count, last_values):
return name
class Direction(AutoName):
NORTH = auto()
SOUTH = auto()
print(Direction.NORTH.value) # NORTH
print(list(Direction)) # [<Direction.NORTH: 'NORTH'>, <Direction.SOUTH: 'SOUTH'>]An enum may be subclassed only if it has no members. That is why the hook lives in AutoName, which has none, and the members live in Direction.
Using `last_values`
The hook can read earlier values, including explicit ones. This example steps by 10 and continues from a manually chosen value.
from enum import Enum, auto
class Step(Enum):
@staticmethod
def _generate_next_value_(name, start, count, last_values):
return last_values[-1] + 10 if last_values else 10
A = auto()
B = auto()
C = 100
D = auto()
print(list(Step))
# [<Step.A: 10>, <Step.B: 20>, <Step.C: 100>, <Step.D: 110>]The if last_values test handles the first member, when the list is still empty. Indexing last_values[-1] on an empty list would raise IndexError.
Rules the hook must respect
- Defining the hook after members does not change those members. In recent Python versions it can also raise an error, so put it first in the class body.
auto()in a mixed enum such asclass Mode(str, Enum)still goes through the hook. If your hook returns an int, the string mixin will try to convert it, which is rarely what you want.- If you assign explicit duplicate values next to generated ones, the usual alias rules apply.
@uniquewill catch the collision.
Combining both hooks
The two hooks work well together when the value is derived from the name and input needs cleaning.
from enum import Enum, auto
class Method(Enum):
@staticmethod
def _generate_next_value_(name, start, count, last_values):
return name
GET = auto()
POST = auto()
@classmethod
def _missing_(cls, value):
if isinstance(value, str):
return cls.__members__.get(value.strip().upper())
return None
print(Method("GET")) # Method.GET (direct match)
print(Method(" post ")) # Method.POST (found by _missing_)
try:
Method("patch")
except ValueError as exc:
print(exc) # 'patch' is not a valid MethodHere _missing_ uses cls.__members__.get(...). Because every value equals its name, the name lookup finds the right member. dict.get returns None for an unknown key, so the unknown-value case falls through to the normal ValueError. This also avoids the recursion problem described earlier.
Choosing between a hook and a plain method
| Need | Use |
|---|---|
| Accept alternate spellings of values | `_missing_` |
| Map every unknown value to a default | `_missing_` returning a sentinel member |
| Parse by name, case-insensitively | A separate classmethod such as `parse` |
| Values derived from names | `_generate_next_value_` |
| Several values per member | Tuple values with `__init__` |
| Fixed, explicit numbers | Plain assignments, no hook |
A separate parse classmethod is easier to read when you want to signal to callers that the input is untrusted. _missing_ changes what Level(...) means everywhere, so use it when that change is what you want.
Common errors, summarized
TypeError: error in Level._missing_: returned ... instead of None or a valid member._missing_returned a non-member. Returncls.SOMETHINGorNone.RecursionErroron a bad value._missing_calledcls(...)with a value that also fails. Search members directly.AttributeErroron non-string input._missing_assumed a string without checking. Addisinstance.- Generated values look wrong. The hook was defined after the members, or
last_valueswas used without handling the empty list. TypeErrorwhen subclassing. The enum already has members. Move the hook to a memberless base class.
Exercise
Write an enum Size with members SMALL, MEDIUM, LARGE whose values are the lowercase names generated automatically, and make Size(" Large ") return Size.LARGE. What happens with Size("huge")?
Show answer
Use a _generate_next_value_ that returns name.lower(), and a _missing_ that strips and lowercases string input and searches the members:
from enum import Enum, auto
class Size(Enum):
@staticmethod
def generatenextvalue(name, start, count, lastvalues):
return name.lower()
SMALL = auto()
MEDIUM = auto()
LARGE = auto()
@classmethod
def missing(cls, value):
if isinstance(value, str):
wanted = value.strip().lower()
for member in cls:
if member.value == wanted:
return member
return None
Size(" Large ") returns Size.LARGE. Size("huge") raises ValueError ("'huge' is not a valid Size") because missing_ returns None. (Python's built-in StrEnum already generates lowercase names, but it does not clean input.)
Exercise
A teammate writes _missing_ as return cls(value.lower()) and calls Level("MEDIUM") on an enum that has no member with the value "medium". What happens, and how do you fix it?
Show answer
The inner cls("medium") fails to match, so _missing_ is called again with "medium". That call lowercases it again and calls cls("medium") once more. The cycle repeats until Python raises RecursionError. The fix is to search the members directly, for example with a loop over cls comparing member.value == value.lower(), and to return None when nothing matches so the normal ValueError is raised.