Sub topic 13
Customizing lookup and value generation
This chapter assumes you can define an Enum, look members up with Color(2) and Color["BLUE"], and use auto(). It also assumes you know what a classmethod is. Two small hooks let you change how an enum finds members and how auto() picks values.
What happens when a value lookup fails
Level("high") is a value lookup. Python first checks the table of member values. If nothing matches, it calls the class method _missing_(value). If that method returns a member, the lookup succeeds. If it returns None, or isn't defined, Python raises ValueError.
Case-insensitive lookup with _missing_
The default lookup is exact. Level("HIGH") fails when the stored value is "high". Override _missing_ to normalize the input and retry:
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 without calling _missing_)
try:
Level("medium")
except ValueError as err:
print(err) # 'medium' is not a valid LevelSome points to keep in mind:
_missing_must be aclassmethod.- Return a member of
cls, not a raw value. Returning anything else raises an error. - Return
Nonefor input you can't handle, so the normalValueErrorstill happens. - Check the type of
valuefirst, as the example does. Callers can pass anything, andvalue.lower()fails on anint.
Choosing values with _generate_next_value_
auto() doesn't pick values itself. It calls _generate_next_value_(name, start, count, last_values) on the class. The default returns 1, 2, 3, and so on. The arguments are:
| Argument | Meaning |
|---|---|
| `name` | The member name being defined |
| `start` | The starting number, 1 by default |
| `count` | How many members exist so far |
| `last_values` | The values of the earlier members |
Override it to produce other values. This version makes each value the lowercase member name:
from enum import Enum, auto
class Fruit(Enum):
def _generate_next_value_(name, start, count, last_values):
return name.lower()
APPLE = auto()
PEAR = auto()
print(Fruit.APPLE.value) # apple
print(Fruit("pear")) # Fruit.PEARThe function takes no self or cls, because it runs while the class body is still being built. Define it before the first member, since auto() calls made earlier won't use it.
A second example continues from the previous value, which is what last_values is for. This one doubles it:
from enum import Enum, auto
class Size(Enum):
def _generate_next_value_(name, start, count, last_values):
if not last_values:
return 10
return last_values[-1] * 2
SMALL = auto()
MEDIUM = auto()
LARGE = auto()
print([m.value for m in Size]) # [10, 20, 40]Common mistakes
- Defining
_generate_next_value_after the members that useauto(). Those members get the default numbers. - Forgetting
@classmethodon_missing_, which makes the hook fail when it is called. - Returning a raw value such as
"high"from_missing_instead ofcls.HIGH. - Expecting
_missing_to affectLevel["HIGH"]or==comparisons. It affects only value lookup.
Exercise
Write a Weekday enum whose values are the integers 1 to 7 for MON through SUN. Add _missing_ so that Weekday("tue") returns Weekday.TUE, and any unknown string still raises ValueError. What must _missing_ return for unknown input?
Show answer
Use MON = 1 through SUN = 7. Define @classmethod def _missing_(cls, value):. Inside it, check isinstance(value, str), then return cls.__members__.get(value.upper()). For unknown input the method must return None. Python then raises ValueError. Since dict.get returns None for a missing key, the code above already does this.