Fixed domain choices
Represent a finite set of states, modes, or categories without scattering string or integer constants through application code.
Python · Class
Enum defines a fixed set of symbolic names associated with values. Its members support identity comparison, iteration, and lookup by value or name.
Subclass Enum to create a class whose named members represent a fixed set of values. Members are singleton objects: compare them by identity, obtain one from its value by calling the enumeration, and access its declared name or value through name and value.
class enum.Enum(*enums)from enum import Enum
class Color(Enum):
RED = "red"
GREEN = "green"
print(Color.RED.name)
print(Color("green") is Color.GREEN)
print([color.value for color in Color])This defines an enumeration, accesses a member name and value, resolves a member from its value, and iterates over the members.
Represent a finite set of states, modes, or categories without scattering string or integer constants through application code.
Use member identity to make state comparisons explicit and type-safe.
Convert serialized values back into strongly named members with Enum(value).
Enum is the base class for creating enumerated constants. Define a subclass and assign names to members, such as RED = 1 and BLUE = 2.
Follow-up: How can a member be retrieved from its value? Call the enumeration class with that value, for example Color(1). If no member has that value, the lookup raises ValueError.
Members are compared by identity, so Color.RED is the appropriate comparison. Each member exposes name, the defining name, and value, the assigned value.
Follow-up: What does iteration return when aliases exist? It returns only canonical members, not aliases, while preserving definition order.
An enumeration can be created with class syntax or with functional syntax such as Enum('Color', [('RED', 1), ('BLUE', 2)]). The functional form returns a new Enum class.
Follow-up: What other lookup syntax is documented? Index syntax retrieves a member by name, for example Color['RED']; an invalid name raises KeyError.
EnumTypeIntEnumFlagIntFlagunique()