On this page
enum
Prev: ensurepip | Up: stdlib_module | Next: errno
Rel: datetime, zoneinfo, calendar, collections, heapq
Ref: docs.python.org — enum
Tags: #public #python3 #stdlib
Import
import enum
Overview
Symbolic, type-safe enumerations (Enum, StrEnum, IntEnum, Flag, auto, @unique) that replace fragile magic strings and integer constants. Prefer StrEnum (Python 3.11+) when enum members need to serialize cleanly as strings in JSON, CLI flags, or URLs.
Quick Start
from enum import StrEnum, auto
class Status(StrEnum):
PENDING = auto() # "pending"
RUNNING = auto() # "running"
DONE = auto() # "done"
assert Status.PENDING == "pending"
assert Status("done") is Status.DONE
Implementation Walkthrough
1. Exhaustive match Dispatch & Custom Behavior on Enum
from enum import Enum
class HttpMethod(Enum):
GET = "GET"
POST = "POST"
DELETE = "DELETE"
@property
def is_safe(self) -> bool:
return self is HttpMethod.GET
def describe(method: HttpMethod) -> str:
match method:
case HttpMethod.GET:
return "read-only"
case HttpMethod.POST | HttpMethod.DELETE:
return "mutating"
assert HttpMethod.GET.is_safe and describe(HttpMethod.POST) == "mutating"
2. Bitwise Permissions with Flag
from enum import Flag, auto
class Perm(Flag):
READ = auto()
WRITE = auto()
EXEC = auto()
rw = Perm.READ | Perm.WRITE
assert Perm.READ in rw and Perm.EXEC not in rw
Gotchas & Boundaries
- Use
isto compareEnummembers:status is Status.DONEis faster and clearer than==. - Duplicate values create aliases silently: Decorate with
@enum.uniquewhen every member must have a distinct value. StrEnum+auto()lowercases member names:Status.PENDING = auto()produces"pending", not"PENDING".- Look up by value vs. by name:
Status("done")looks up by value;Status["DONE"]looks up by member name.
Common Functions
- enum.global_enum() —
global_enum(cls, update_str=False)— decorator that makes the repr() of an enum member reference its module instead of its class; also exports all members to the enum's module's global namespace - enum.global_enum_repr() —
global_enum_repr(self)— use module.enum_name instead of class.enum_name the module is the last module in case of a multi-module name - enum.global_flag_repr() —
global_flag_repr(self)— use module.flag_name instead of class.flag_name the module is the last module in case of a multi-module name - enum.global_str() —
global_str(self)— use enum_name instead of class.enum_name - enum.pickle_by_enum_name() —
pickle_by_enum_name(self, proto)—enum.pickle_by_enum_name()function. - enum.pickle_by_global_name() —
pickle_by_global_name(self, proto)—enum.pickle_by_global_name()function. - enum.unique() —
unique(enumeration)— Class decorator for enumerations ensuring unique member values.
Classes & Objects
- enum.auto — Instances are replaced with an appropriate value in Enum class suites.
- enum.Enum — Create a collection of name/value pairs.
- enum.EnumCheck — various conditions to check an enumeration for (Methods:
.capitalize(),.casefold(),.center(),.count(),.encode(),.endswith()) - enum.EnumDict — Track enum member order and ensure member names are not reused. (Methods:
.clear(),.copy(),.fromkeys(),.get(),.items(),.keys()) - enum.EnumMeta — Metaclass for Enum (Methods:
.mro()) - enum.EnumType — Metaclass for Enum (Methods:
.mro()) - enum.Flag — Support for flags
- enum.FlagBoundary — control how out of range values are handled "strict" -> error is raised [default for Flag] "conform" -> extra bits are discarded (Methods:
.capitalize(),.casefold(),.center(),.count(),.encode(),.endswith()) - enum.IntEnum — Enum where members are also (and must be) ints (Methods:
.as_integer_ratio(),.bit_count(),.bit_length(),.conjugate(),.from_bytes(),.is_integer()) - enum.IntFlag — Support for integer-based Flags (Methods:
.as_integer_ratio(),.bit_count(),.bit_length(),.conjugate(),.from_bytes(),.is_integer()) - enum.member — Forces item to become an Enum member during class creation.
- enum.nonmember — Protects item from becoming an Enum member during class creation.
- enum.property — This is a descriptor, used to define attributes that act differently when accessed through an enum member and through an enum class. (Methods:
.deleter(),.getter(),.setter()) - enum.ReprEnum — Only changes the repr(), leaving str() and format() to the mixed-in type.
- enum.StrEnum — Enum where members are also (and must be) strings (Methods:
.capitalize(),.casefold(),.center(),.count(),.encode(),.endswith()) - enum.verify — Check an enumeration for various constraints. (see EnumCheck)
Constants & Attributes
enum.CONFORM(FlagBoundary) =<FlagBoundary.CONFORM: 'conform'>enum.CONTINUOUS(EnumCheck) =<EnumCheck.CONTINUOUS: 'no skipped integer values'>enum.EJECT(FlagBoundary) =<FlagBoundary.EJECT: 'eject'>enum.KEEP(FlagBoundary) =<FlagBoundary.KEEP: 'keep'>enum.NAMED_FLAGS(EnumCheck) =<EnumCheck.NAMED_FLAGS: 'multi-flag aliases may not conta...enum.STRICT(FlagBoundary) =<FlagBoundary.STRICT: 'strict'>enum.UNIQUE(EnumCheck) =<EnumCheck.UNIQUE: 'one name per value'>
Linked from
Related notes
- tuts/python3/stdlib_module/ensurepip Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/errno Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/calendar Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/collections Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/datetime Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/enum/auto Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/enum/Enum Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/enum/EnumCheck Linked here; shared tags: #stdlib