Sub topic 2
Reading names and values, and looking members up
This chapter assumes you can define a basic Enum class and that you know how classes, attributes and exceptions work. It covers how to read a member's name and value, and how to find a member from either one.
Members are class attributes
Each name in an enum body becomes a member. You reach a member through the class, and each member is an instance of that class.
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
print(Color.RED) # Color.RED
print(Color.RED.name) # RED
print(Color.RED.value) # 1
print(Color(2)) # Color.GREEN
print(Color["BLUE"]) # Color.BLUEThe print(Color.RED) line shows the member's readable form, Color.RED. It does not show the value. The two attributes you will use most are:
.nameis the member's name as a string..valueis the value you assigned in the class body.
print(type(Color.RED)) # <enum 'Color'>
print(isinstance(Color.RED, Color)) # True
print(repr(Color.RED)) # <Color.RED: 1>The repr form includes both name and value, which makes it the most useful one when debugging.
Two ways to look a member up
Sometimes you hold a raw value, such as a number read from a file. Sometimes you hold a name, such as a string from a config. The enum class supports both lookups.
| You have | Syntax | Example | Result |
|---|---|---|---|
| A value | Call the class | `Color(2)` | `Color.GREEN` |
| A name | Index the class | `Color["BLUE"]` | `Color.BLUE` |
The call form Color(2) searches by value. The index form Color["BLUE"] searches by name. Mixing them up is a common mistake: Color("BLUE") looks for a member whose value is the string "BLUE", and it fails here.
Handling failed lookups
The two lookups raise different exceptions when nothing matches.
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
try:
Color(99)
except ValueError as e:
print("value error:", e)
try:
Color["PURPLE"]
except KeyError as e:
print("key error:", e)A missing value raises ValueError. A missing name raises KeyError. Catch the one that matches the lookup you used.
Enum classes have no .get() method. If you want a default instead of an exception, write a small helper.
def parse_color(raw):
try:
return Color(raw)
except ValueError:
return None
print(parse_color(2)) # Color.GREEN
print(parse_color(42)) # NoneFor names, you can check against __members__ first, or catch KeyError in the same way.
print("RED" in Color.__members__) # True
print("PURPLE" in Color.__members__) # FalseMembers are not their values
A member wraps a value, but it is a different object. Comparing a member with its raw value gives False.
print(Color.RED == 1) # False
print(Color.RED.value == 1) # TrueWhen you receive raw data, convert it once at the boundary with Color(raw). After that, work with members and compare members to members. Use .value only when you need to send the data out again, for example when writing JSON.
import json
stored = json.dumps({"color": Color.GREEN.value})
print(stored) # {"color": 2}
loaded = Color(json.loads(stored)["color"])
print(loaded) # Color.GREENMembers cannot be changed
You cannot reassign a member or its attributes through the class. This protects you from accidentally redefining a constant.
try:
Color.RED = 5
except AttributeError as e:
print("error:", e)The assignment raises AttributeError. The exact message differs between Python versions, so rely on the exception type and not the text.
Exercise
A config file contains the string "GREEN" and a database column contains the integer 3. Using the Color enum from this chapter, write the two expressions that turn each into a member. What does each raise if the data is wrong?
Show answer
Use Color["GREEN"] for the string, since it is a name, and Color(3) for the integer, since it is a value. Color["GREEN"] raises KeyError if the name does not exist, and Color(3) raises ValueError if no member has that value. Here Color["GREEN"] returns Color.GREEN and Color(3) returns Color.BLUE.
Exercise
Why does Color.RED == 1 print False, and how would you get a True result without changing the enum?
Show answer
A plain Enum member is a distinct object from its value, so it does not equal the raw integer. Compare the value instead with Color.RED.value == 1, or convert the integer to a member first with Color(1) == Color.RED.