Sub topic 3
Iterating over members and understanding aliases
This chapter assumes you can define a basic Enum class and read .name and .value. It also assumes you know the difference between == and is, and that you can loop over a collection. By the end you will know which members iteration returns and which it skips. You will also know how Python decides that a name is an alias, and how to find aliases in your own enums.
Iterating over an enum class
An enum class is iterable. Looping over the class itself, not over an instance, yields its members in the order they were defined.
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
for color in Color:
print(color.name, color.value)
print(list(Color))
print(len(Color))
print(Color.GREEN in Color)
print(list(reversed(Color)))This prints:
RED 1
GREEN 2
BLUE 3
[<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 3>]
3
True
[<Color.BLUE: 3>, <Color.GREEN: 2>, <Color.RED: 1>]The class supports for loops, list(), len(), in and reversed(). Python gets this from the metaclass, EnumType (called EnumMeta before Python 3.11). Because iteration is defined on the class, Color is the iterable. Members such as Color.RED are not iterable.
Definition order is part of the behavior. Code such as menu builders, documentation generators and serializers can rely on it. You do not need to sort the members to get a stable order.
Common iteration patterns
You can build lookups and choice lists with ordinary comprehensions:
names = [c.name for c in Color]
values = [c.value for c in Color]
by_value = {c.value: c for c in Color}
choices = [(c.value, c.name.title()) for c in Color]
print(names) # ['RED', 'GREEN', 'BLUE']
print(values) # [1, 2, 3]
print(choices) # [(1, 'Red'), (2, 'Green'), (3, 'Blue')]Remember that Color(2) and Color["BLUE"] already do value and name lookups. You rarely need to build your own by_value dictionary unless you want a different key, such as a lowercase label.
What aliases are
Two names in the same enum can have the same value. Python does not create two members in that case. The first name defined becomes the real member (the canonical one). Every later name with an equal value becomes an alias, a second name that points to the same member object.
from enum import Enum
class Status(Enum):
ACTIVE = 1
ENABLED = 1 # alias of ACTIVE
DISABLED = 2
print(Status.ENABLED is Status.ACTIVE) # True
print(Status.ENABLED) # Status.ACTIVE
print(Status.ENABLED.name) # ACTIVE
print(Status(1)) # Status.ACTIVE
print(Status["ENABLED"]) # Status.ACTIVE
print(list(Status)) # [<Status.ACTIVE: 1>, <Status.DISABLED: 2>]
print(len(Status)) # 2Status.ENABLED is not a second object that happens to look like ACTIVE. It is the same object, so is returns True. Its .name is "ACTIVE", not "ENABLED". Python only stores one name per member, and that name is the canonical one.
The decision happens while the class body is processed, one name at a time:
Equality decides, not identity
Python compares values with == (after checking that they hash the same, for hashable values). Values that are different objects but compare equal still produce an alias:
from enum import Enum
class Weird(Enum):
ONE = 1
UNO = 1.0
YES = True
print(list(Weird)) # [<Weird.ONE: 1>]
print(Weird.UNO is Weird.ONE) # True
print(Weird.YES is Weird.ONE) # True1 == 1.0 == True in Python, so all three names refer to one member. This is rarely what you want. It is one reason to be careful when mixing numeric types in an enum.
Unhashable values, such as lists, cannot use that fast comparison. Python falls back to a linear search with ==, so aliasing still works for them, only more slowly.
`__members__`: the complete view
Iteration hides aliases. To see every name, including aliases, use the class attribute __members__. It is a read-only mapping from each name to its member. Aliases appear as extra keys that map to a member whose .name differs from the key.
for name, member in Status.__members__.items():
print(f"{name:9} -> {member!r}")ACTIVE -> <Status.ACTIVE: 1>
ENABLED -> <Status.ACTIVE: 1>
DISABLED -> <Status.DISABLED: 2>Compare the key with member.name to find aliases:
aliases = {
name: member.name
for name, member in Status.__members__.items()
if name != member.name
}
print(aliases) # {'ENABLED': 'ACTIVE'}The result maps each alias to the canonical name it points to. This is a good check to run in a test if your team depends on the enum having no aliases.
The mapping is read-only (it is a mappingproxy), so you cannot add or remove names through it.
Which operations see aliases
| Operation | Includes aliases? | Notes |
|---|---|---|
| `for m in Status` | No | Canonical members only, in definition order |
| `list(Status)` | No | Same as iteration |
| `len(Status)` | No | Counts canonical members |
| `reversed(Status)` | No | Canonical members, last to first |
| `Status.__members__` | Yes | Keys are every defined name |
| `Status["ENABLED"]` | Yes | Returns the canonical member |
| `Status(1)` | Not applicable | Looks up by value and returns the canonical member |
An alias is therefore only a second spelling for lookup by name. Nothing else treats it as a separate item.
Why aliases exist
Aliases are a deliberate feature. Two uses come up in real code.
- Renaming without breaking callers. You decide
ENABLEDis a clearer name thanACTIVE. Keep the old name as an alias, and existing code that usesStatus.ACTIVEkeeps working. - Several names for one concept. Some domains use synonyms, for example HTTP-style names or compass abbreviations.
from enum import Enum
class Shape(Enum):
SQUARE = 2
DIAMOND = 1
CIRCLE = 3
ALIAS_FOR_SQUARE = 2
print(Shape.ALIAS_FOR_SQUARE) # Shape.SQUARE
print(list(Shape))
# [<Shape.SQUARE: 2>, <Shape.DIAMOND: 1>, <Shape.CIRCLE: 3>]The alias can come after other members. What matters is that its value matches an earlier member. The first name with that value wins, whatever its position among the other members.
Aliases as a source of bugs
Aliases cause trouble when you did not intend them. A copy-and-paste slip creates one silently:
from enum import Enum
class Level(Enum):
DEBUG = 10
INFO = 20
WARNING = 20 # typo: should be 30
ERROR = 40
print(list(Level))
# [<Level.DEBUG: 10>, <Level.INFO: 20>, <Level.ERROR: 40>]
print(Level.WARNING) # Level.INFONo error is raised. Level.WARNING quietly becomes Level.INFO, and a loop over Level has only three entries. A menu built from iteration would be missing "WARNING", and any code that compares against Level.WARNING would treat INFO messages as warnings.
Three habits protect you from this:
- Compare
len(Level)withlen(Level.__members__)in a test. If they differ, the enum has aliases. - Use the
@uniquedecorator when you want aliases forbidden. The next chapter covers it. - When you do want aliases, add a comment, as in the examples above.
A short helper makes the first check reusable:
from enum import Enum
def has_aliases(enum_cls: type[Enum]) -> bool:
return len(enum_cls.__members__) != len(enum_cls)
print(has_aliases(Level)) # True
print(has_aliases(Status)) # TrueMembership tests
member in EnumClass is straightforward for members. Testing a raw value depends on your Python version:
from enum import Enum
class Color(Enum):
RED = 1
print(Color.RED in Color) # TrueIn Python 3.8 to 3.11, 1 in Color raises TypeError because 1 is not a member. In Python 3.12 and later, 1 in Color returns True because it checks values as well. Code that must work across versions should avoid testing raw values with in. Look the value up instead and catch the error:
def is_valid_color(value) -> bool:
try:
Color(value)
except ValueError:
return False
return True
print(is_valid_color(1)) # True
print(is_valid_color(9)) # FalseColor(value) raises ValueError when no member has that value. Aliases do not change this, since lookup by value always finds the canonical member.
Exercises
Exercise
Given the enum below, what do len(Http), list(Http) and list(Http.__members__) return, and what is Http.MISSING.name?
class Http(Enum):
OK = 200
SUCCESS = 200
NOT_FOUND = 404
MISSING = 404
Show answer
len(Http) is 2. list(Http) is [<Http.OK: 200>, <Http.NOT_FOUND: 404>]. list(Http.__members__) is ['OK', 'SUCCESS', 'NOT_FOUND', 'MISSING']. Http.MISSING.name is 'NOT_FOUND', because MISSING is an alias and a member has only its canonical name.
Exercise
Write a function alias_map(enum_cls) that returns a dictionary mapping each alias name to the canonical name it refers to. What does it return for Status from this chapter?
Show answer
Use __members__ and compare each key with the member's .name:
def aliasmap(enumcls):
return {
name: member.name
for name, member in enumcls.members_.items()
if name != member.name
}
For Status it returns {'ENABLED': 'ACTIVE'}. An enum with no aliases returns an empty dictionary.