On this page
  1. enum
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Exhaustive match Dispatch & Custom Behavior on Enum
  7. 2. Bitwise Permissions with Flag
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects
  11. Constants & Attributes

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

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes