Python Reference ยท Standard Library: Data Structures and Functional Tools
The enum module
Reference for Python's enum module: Enum, IntEnum, StrEnum, Flag, auto(), lookup by value or name, aliases, unique and members with methods.
The enum module lets you define a fixed set of named constants as a class. Each constant is a unique, immutable member that knows its name and value, prints readably and can be compared by identity. Enumerations replace scattered magic strings and numbers like "pending" or 3 with names that the editor can complete and that typos cannot silently break.
You define one by subclassing Enum (or one of its variants) and listing members as class attributes. Members are created once; looking one up by value or name always returns the same object.
from enum import Enum class Color(Enum): RED = 1 GREEN = 2
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
What is in the module
| Name | Description |
|---|---|
Enum |
Base class for ordinary enumerations. Members are compared by identity and are not orderable. |
IntEnum |
Members are also int, so they compare and calculate like integers. |
StrEnum |
Members are also str (added in 3.11). With auto(), the value is the lower-cased member name. |
Flag |
Members can be combined with |, &, ^ and ~ as bit flags. |
IntFlag |
Like Flag, but members are also integers. |
auto() |
Picks the next value automatically (1, 2, 3, ... for Enum; powers of two for Flag). |
unique |
Class decorator that raises ValueError if two names share a value. |
member / nonmember |
Mark an attribute explicitly as a member or as a plain attribute (3.11). |
verify, EnumCheck |
Decorator and options for checks such as continuous values (3.11). |
EnumType |
The metaclass of enumerations (named EnumMeta before 3.11). |
Functional API: Enum("Color", "RED GREEN BLUE") creates an enum without a class statement. Values start at 1.
Usage notes
- Look up by value with
Color(1), by name withColor["RED"]. A missing value raisesValueError; a missing name raisesKeyError. Override_missing_to customize value lookup. - Members are singletons. Compare with
isor==; both work. An ordinaryEnumdoes not equal its raw value (Status.ACTIVE == "active"isFalse). UseIntEnumorStrEnumwhen interoperability with plain numbers or strings matters. - Aliases. If two names have the same value, the second becomes an alias for the first and does not appear when iterating.
__members__includes aliases. - Iteration is in definition order and excludes aliases.
len(Status)counts real members. - Enums are immutable. You cannot reassign a member or add one after the class is created, and a class that already has members cannot be subclassed.
- Methods, properties and class methods are allowed. Functions defined in the class body become methods, not members. Plain values (numbers, strings, tuples) become members.
- Tuple values are passed to
__init__if you define one, which lets members carry several fields. Flagmembers supportin,|,&,^. A combination such asREAD | WRITEhas no name of its own but still is aFlaginstance.IntEnumcaveat. Because members equal integers,Level.LOW == Priority.LOWcan be true across unrelated enums. Prefer plainEnumunless you need numeric behavior.- Serialization.
json.dumpsacceptsIntEnumandStrEnummembers directly; for plainEnum, dumpmember.value. - Pattern matching works with qualified names:
case Status.DONE:.
Related
dataclasses,typing,classint,str- Lessons: Enums, Classes, match statements