Sub topic 2
Reading names and values, and looking members up
This chapter assumes you can define a simple Enum class, as covered in the previous chapter, and that you know the difference between == and is. Here you will learn how to get at a member's name and value, how to find a member from a name or a value, and what happens when the lookup fails.
Members are class attributes
Each name you define in an Enum body becomes a member. You reach a member as an attribute of the class.
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
red = Color.RED
print(red) # Color.RED
print(repr(red)) # <Color.RED: 1>
print(type(red)) # <enum 'Color'>
print(red.name) # RED
print(red.value) # 1
print(isinstance(red, Color)) # TrueColor.RED is an instance of Color, not an integer. It carries two read-only attributes:
nameis astrholding the name used in the class body.valueis whatever object you assigned on the right-hand side.
The str() form is Color.RED, which is handy in logs. The repr() form also shows the value, which is handy in a debugger.
Values are not limited to integers. They can be strings, floats, tuples or other objects, and different members of one enum may even hold different types. Mixing types is rarely a good idea, because it makes the enum harder to reason about.
from enum import Enum
class Level(Enum):
LOW = "low"
HIGH = "high"
print(Level.HIGH.value) # high
print(Level.HIGH.name.lower()) # highMembers cannot be changed
Members and their attributes are protected from reassignment. Both of these raise AttributeError:
from enum import Enum
class Color(Enum):
RED = 1
try:
Color.RED = 5
except AttributeError as exc:
print("cannot rebind a member")
try:
Color.RED.value = 5
except AttributeError as exc:
print("cannot change a value")This protection is part of why enum members are safe to use as constants and as dictionary keys.
Three ways to find a member
Sometimes you do not have the member in hand. You have a number from a database, or a string from a config file. The enum class supports three lookups.
| Form | You have | Example | Failure |
|---|---|---|---|
| Attribute access | A name written in source code | `Color.GREEN` | `AttributeError` |
| Call syntax | A value | `Color(2)` | `ValueError` |
| Item syntax | A name held in a variable | `Color["BLUE"]` | `KeyError` |
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
print(Color(2)) # Color.GREEN
print(Color["BLUE"]) # Color.BLUE
wanted = "RED"
print(Color[wanted]) # Color.REDUse attribute access when the name is fixed in your code. Use Color(value) when the data comes from outside and holds the stored value. Use Color[name] when the data holds the member's name.
Why call syntax works
Color(2) looks like it creates a new object, but it does not. The enum's metaclass intercepts the call and returns the one existing member whose value is 2. Calling it twice gives the same object:
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
print(Color(2) is Color(2)) # True
print(Color(Color.RED) is Color.RED) # TruePassing a member to the class returns that same member. This makes it easy to write functions that accept either a raw value or a member and normalize both.
Value lookup uses == and hashing, so Color(2.0) also finds Color.GREEN, because 2.0 == 2. The lookup does not convert types for you in any other way. Color("2") fails, because the string "2" is not equal to the integer 2.
When lookups fail
Each lookup form raises a different exception, so catch the right one.
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
for attempt in (lambda: Color.PURPLE,
lambda: Color(9),
lambda: Color["PURPLE"]):
try:
attempt()
except (AttributeError, ValueError, KeyError) as exc:
print(type(exc).__name__, "-", exc)The output looks like this, with slightly different wording between Python versions:
AttributeError - type object 'Color' has no attribute 'PURPLE'
ValueError - 9 is not a valid Color
KeyError - 'PURPLE'Name lookup is case-sensitive. Color["red"] raises KeyError even though RED exists. If your input may vary in case, normalize it first, for example with Color[text.upper()].
Returning a default instead of raising
Enums have no built-in get() method like a dictionary. Two patterns fill the gap.
For names, use the __members__ mapping, which is described below:
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
print(Color.__members__.get("PURPLE")) # None
print(Color.__members__.get("RED")) # Color.REDFor values, wrap the call in a small helper function:
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
def color_or_none(value):
try:
return Color(value)
except ValueError:
return None
print(color_or_none(2)) # Color.GREEN
print(color_or_none(7)) # NoneCatch ValueError only. A broad except Exception would hide real bugs in the lookup code.
The last chapters of this tutorial show how to put this fallback inside the enum class itself using _missing_.
The `__members__` mapping
Every enum class has a __members__ attribute. It is a read-only mapping from each name to its member, and it includes aliases (names that share a value with an earlier member).
from enum import Enum
class Status(Enum):
ACTIVE = 1
ENABLED = 1 # alias of ACTIVE
DISABLED = 2
print(list(Status.__members__))
# ['ACTIVE', 'ENABLED', 'DISABLED']
for name, member in Status.__members__.items():
print(name, "->", member.name)
# ACTIVE -> ACTIVE
# ENABLED -> ACTIVE
# DISABLED -> DISABLEDThe second loop line shows the key point about aliases: Status.ENABLED is the same object as Status.ACTIVE, so its name is ACTIVE. The first name defined for a value is the canonical name.
Lookups follow from this:
print(Status(1)) # Status.ACTIVE
print(Status["ENABLED"]) # Status.ACTIVE
print(Status.ENABLED.name) # ACTIVELooking up by the value 1 always gives the canonical member. Looking up by the alias name also gives the canonical member. Plain iteration, with list(Status), skips aliases and yields only canonical members. The next chapter covers iteration in detail.
Building a lookup from external text
A common job is parsing user or file input into members. This function combines the ideas above and fails with a clear message.
from enum import Enum
class Level(Enum):
LOW = "low"
HIGH = "high"
def parse_level(text: str) -> Level:
try:
return Level(text.strip().lower())
except ValueError:
allowed = ", ".join(m.value for m in Level)
raise ValueError(f"unknown level {text!r}; expected one of: {allowed}") from None
print(parse_level(" HIGH ")) # Level.HIGH
try:
parse_level("medium")
except ValueError as exc:
print(exc) # unknown level 'medium'; expected one of: low, highListing the allowed values in the message turns a bare ValueError into something a user can act on.
Pitfalls with name and value lookups
Other points to keep in mind:
member.nameis always astr, butmember.valuecan be any type. Do not assume you can call string methods on a value without checking the enum's definition.- Comparing a member to its raw value, as in
Color.RED == 1, givesFalsefor a plainEnum. Look up first withColor(1), or compareColor.RED.value == 1. - Value lookup accepts any equal value, so
Color(True)returnsColor.REDwhenRED = 1. This surprises people who pass booleans by mistake. - Aliases do not appear when you iterate, so code that builds a name list from iteration can miss a name that
Color["ALIAS"]would accept.
Exercises
Exercise
Given class Size(Enum): SMALL = "S"; LARGE = "L", write the expression that returns Size.LARGE from the string "L", and the expression that returns it from the string "LARGE". Which exception does each raise if the input is wrong?
Show answer
Size("L") looks up by value and raises ValueError on bad input. Size["LARGE"] looks up by name and raises KeyError on bad input.
Exercise
In this enum, what do Mode(1), Mode["EDIT"] and Mode.EDIT.name return? Why?
class Mode(Enum):
WRITE = 1
EDIT = 1
READ = 2
Show answer
All three refer to Mode.WRITE or its name. EDIT is an alias because its value 1 was already used by WRITE. Mode(1) returns Mode.WRITE, Mode["EDIT"] returns Mode.WRITE, and Mode.EDIT.name is the string "WRITE".
Exercise
Write a function safe_name(name) for the Color enum above that returns the member for a name, or None if the name does not exist, without using try/except.
Show answer
def safe_name(name): return Color.__members__.get(name). The __members__ mapping supports .get(), which returns None for a missing key.