Claude Code for enum: Symbolic Constants and State Machines in Python — Claude Skills 360 Blog
Blog / AI / Claude Code for enum: Symbolic Constants and State Machines in Python
AI

Claude Code for enum: Symbolic Constants and State Machines in Python

Published: July 3, 2028
Read time: 5 min read
By: Claude Skills 360

enum provides symbolic named constants that can be compared, iterated, and serialized. from enum import Enum, IntEnum, StrEnum, Flag, IntFlag, auto, unique. Enum: class Color(Enum): RED=1; GREEN=2; BLUE=3. Access: Color.RED; Color["RED"]; Color(1). Name/value: Color.RED.name → "RED"; Color.RED.value → 1. Iterate: list(Color). Membership: Color.RED in Color. IntEnum: class Status(IntEnum): OK=200; NOT_FOUND=404 — works as int in comparisons. StrEnum: class Dir(StrEnum): NORTH="north" (Python 3.11+) — works as str. auto: class Priority(Enum): LOW=auto(); MEDIUM=auto(); HIGH=auto() — auto sequential values. Flag: class Perm(Flag): READ=auto(); WRITE=auto(); EXEC=auto(); RWX=READ|WRITE|EXEC. IntFlag: same but int-compatible. unique: @unique class X(Enum): A=1; B=1 — raises ValueError. missing: classmethod for unknown value handling. generate_next_value: customize auto. aliases: B=1; C=1 — C is alias for B. Functional API: Status = Enum("Status",["OPEN","CLOSED"]). mixin: class Color(str, Enum): RED="red" — StrEnum pattern pre-3.11. @property: add computed attributes to members. list(Perm) — only canonical members. Perm.READ|Perm.WRITE — compound flag. Perm.READ in Perm.RWX — membership test. Claude Code generates HTTP status enums, state machines, permission flags, and config constant registries.

CLAUDE.md for enum

## enum Stack
- Stdlib: from enum import Enum, IntEnum, StrEnum, Flag, IntFlag, auto, unique
- Basic: class Status(Enum): OPEN=auto() | CLOSED=auto()
- Int: class HTTPStatus(IntEnum): OK=200 | NOT_FOUND=404  — use when int comparison needed
- Str: class Direction(StrEnum): NORTH="north"  (Python 3.11+)
- Flag: class Permission(Flag): READ=auto() | WRITE=auto()  — combine with |
- Parse: Status("open") | Status["OPEN"] | Status._missing_(val) for lenient parsing

enum Constant and State Machine Pipeline

# app/enums.py — Enum, IntEnum, StrEnum, Flag, auto, state machine, HTTP status
from __future__ import annotations

from enum import (
    Enum,
    Flag,
    IntEnum,
    IntFlag,
    auto,
    unique,
)
from typing import Any, Iterator


# ─────────────────────────────────────────────────────────────────────────────
# 1. Basic enums
# ─────────────────────────────────────────────────────────────────────────────

@unique
class Color(Enum):
    """
    RGB color constants.

    Example:
        c = Color.RED
        print(c.name, c.value)      # RED 1
        print(Color["RED"])         # Color.RED
        print(Color(2))             # Color.GREEN
        print(list(Color))          # [Color.RED, Color.GREEN, Color.BLUE]
    """
    RED   = 1
    GREEN = 2
    BLUE  = 3

    def to_hex(self) -> str:
        mapping = {1: "#FF0000", 2: "#00FF00", 3: "#0000FF"}
        return mapping[self.value]

    @classmethod
    def from_hex(cls, hex_code: str) -> Color:
        mapping = {"#ff0000": cls.RED, "#00ff00": cls.GREEN, "#0000ff": cls.BLUE}
        result = mapping.get(hex_code.lower())
        if result is None:
            raise ValueError(f"Unknown hex color: {hex_code!r}")
        return result


class Priority(Enum):
    """
    Task priority using auto() values.

    Example:
        p = Priority.HIGH
        sorted_tasks = sorted(tasks, key=lambda t: t.priority.value)
    """
    LOW    = auto()   # 1
    MEDIUM = auto()   # 2
    HIGH   = auto()   # 3
    URGENT = auto()   # 4

    def __lt__(self, other: Priority) -> bool:
        return self.value < other.value


# ─────────────────────────────────────────────────────────────────────────────
# 2. IntEnum — integer-compatible
# ─────────────────────────────────────────────────────────────────────────────

class HTTPStatus(IntEnum):
    """
    Common HTTP status codes. Inherits int so it works wherever int is expected.

    Example:
        status = HTTPStatus.OK
        assert status == 200          # int comparison works
        assert status < 300           # ordering works
        assert HTTPStatus(404) == HTTPStatus.NOT_FOUND
        assert HTTPStatus.OK.phrase   # "OK"
    """
    # 2xx
    OK                   = 200
    CREATED              = 201
    ACCEPTED             = 202
    NO_CONTENT           = 204
    # 3xx
    MOVED_PERMANENTLY    = 301
    NOT_MODIFIED         = 304
    # 4xx
    BAD_REQUEST          = 400
    UNAUTHORIZED         = 401
    FORBIDDEN            = 403
    NOT_FOUND            = 404
    METHOD_NOT_ALLOWED   = 405
    CONFLICT             = 409
    UNPROCESSABLE_ENTITY = 422
    TOO_MANY_REQUESTS    = 429
    # 5xx
    INTERNAL_SERVER_ERROR = 500
    BAD_GATEWAY          = 502
    SERVICE_UNAVAILABLE  = 503

    @property
    def phrase(self) -> str:
        return self.name.replace("_", " ").title()

    @property
    def is_success(self) -> bool:
        return 200 <= self.value < 300

    @property
    def is_client_error(self) -> bool:
        return 400 <= self.value < 500

    @property
    def is_server_error(self) -> bool:
        return 500 <= self.value < 600

    @classmethod
    def _missing_(cls, value: object) -> HTTPStatus | None:
        """Return None for unknown status codes instead of raising ValueError."""
        return None


# ─────────────────────────────────────────────────────────────────────────────
# 3. StrEnum-style (str mixin, Python 3.10 compatible)
# ─────────────────────────────────────────────────────────────────────────────

class Environment(str, Enum):
    """
    Deployment environment — works as a string everywhere.

    Example:
        env = Environment.PRODUCTION
        assert env == "production"        # str comparison
        assert env.upper() == "PRODUCTION"  # str methods
        print(f"Deploying to {env}")      # "Deploying to production"
    """
    DEVELOPMENT = "development"
    STAGING     = "staging"
    PRODUCTION  = "production"
    TEST        = "test"

    @property
    def is_prod_like(self) -> bool:
        return self in (Environment.STAGING, Environment.PRODUCTION)

    @property
    def log_level(self) -> str:
        return "DEBUG" if self == Environment.DEVELOPMENT else "INFO"

    @classmethod
    def _missing_(cls, value: object) -> Environment | None:
        if isinstance(value, str):
            for member in cls:
                if member.value == value.lower():
                    return member
        return None


# ─────────────────────────────────────────────────────────────────────────────
# 4. Flag — bitmask combinations
# ─────────────────────────────────────────────────────────────────────────────

class Permission(Flag):
    """
    File/resource permissions as composable flags.

    Example:
        perm = Permission.READ | Permission.WRITE
        assert Permission.READ in perm
        assert Permission.EXEC not in perm
        print(perm)           # Permission.READ|WRITE
        rw = Permission.RW
        assert rw == (Permission.READ | Permission.WRITE)
    """
    NONE  = 0
    READ  = auto()
    WRITE = auto()
    EXEC  = auto()
    # Compound aliases
    RW    = READ  | WRITE
    RX    = READ  | EXEC
    RWX   = READ  | WRITE | EXEC

    def allows(self, required: Permission) -> bool:
        return (self & required) == required

    @classmethod
    def from_octal(cls, octal: int) -> Permission:
        """
        Parse Unix octal permission: 7=RWX, 6=RW, 5=RX, 4=R, 1=X.

        Example:
            Permission.from_octal(6)   # Permission.READ|WRITE
        """
        perm = cls.NONE
        if octal & 4:
            perm |= cls.READ
        if octal & 2:
            perm |= cls.WRITE
        if octal & 1:
            perm |= cls.EXEC
        return perm

    def to_octal(self) -> int:
        val = 0
        if Permission.READ in self:
            val += 4
        if Permission.WRITE in self:
            val += 2
        if Permission.EXEC in self:
            val += 1
        return val


class LogLevel(IntFlag):
    """
    Log level flags usable as integer bitmask.

    Example:
        active = LogLevel.INFO | LogLevel.ERROR
        assert LogLevel.INFO in active
        assert LogLevel.DEBUG not in active
    """
    NOTSET   = 0
    DEBUG    = 10
    INFO     = 20
    WARNING  = 30
    ERROR    = 40
    CRITICAL = 50


# ─────────────────────────────────────────────────────────────────────────────
# 5. State machine
# ─────────────────────────────────────────────────────────────────────────────

class OrderStatus(Enum):
    """
    Order lifecycle states with allowed transitions.

    Example:
        order = OrderStatus.PENDING
        order = order.transition_to(OrderStatus.CONFIRMED)
        order = order.transition_to(OrderStatus.SHIPPED)
        # order.transition_to(OrderStatus.PENDING)  → raises ValueError
    """
    PENDING   = "pending"
    CONFIRMED = "confirmed"
    SHIPPED   = "shipped"
    DELIVERED = "delivered"
    CANCELLED = "cancelled"
    REFUNDED  = "refunded"

    # Allowed (from → set_of_tos)
    _TRANSITIONS: dict = {}  # populated below

    def can_transition_to(self, next_state: OrderStatus) -> bool:
        allowed = {
            OrderStatus.PENDING:   {OrderStatus.CONFIRMED, OrderStatus.CANCELLED},
            OrderStatus.CONFIRMED: {OrderStatus.SHIPPED,   OrderStatus.CANCELLED},
            OrderStatus.SHIPPED:   {OrderStatus.DELIVERED, OrderStatus.CANCELLED},
            OrderStatus.DELIVERED: {OrderStatus.REFUNDED},
            OrderStatus.CANCELLED: set(),
            OrderStatus.REFUNDED:  set(),
        }
        return next_state in allowed.get(self, set())

    def transition_to(self, next_state: OrderStatus) -> OrderStatus:
        if not self.can_transition_to(next_state):
            raise ValueError(
                f"Invalid transition: {self.value!r}{next_state.value!r}"
            )
        return next_state

    @property
    def is_terminal(self) -> bool:
        return self in (OrderStatus.DELIVERED, OrderStatus.CANCELLED, OrderStatus.REFUNDED)

    @property
    def label(self) -> str:
        return self.value.replace("_", " ").capitalize()


# ─────────────────────────────────────────────────────────────────────────────
# 6. Lenient parsing helper
# ─────────────────────────────────────────────────────────────────────────────

def parse_enum(cls: type[Enum], value: Any, default=None) -> Any:
    """
    Parse a string or int into an enum member; return default if not found.

    Example:
        parse_enum(Color, "RED")   # Color.RED
        parse_enum(Color, 1)       # Color.RED
        parse_enum(Color, "X", default=Color.BLUE)  # Color.BLUE
    """
    with suppress_value_errors():
        if isinstance(value, cls):
            return value
        try:
            return cls(value)
        except (ValueError, KeyError):
            pass
        if isinstance(value, str):
            try:
                return cls[value.upper()]
            except KeyError:
                pass
    return default


from contextlib import suppress as suppress_value_errors  # noqa: E402


def enum_choices(cls: type[Enum]) -> list[str]:
    """
    Return list of all member names — useful for argparse/click choices.

    Example:
        parser.add_argument("--env", choices=enum_choices(Environment))
    """
    return [m.name for m in cls]


def enum_values(cls: type[Enum]) -> list[Any]:
    """Return list of all member values."""
    return [m.value for m in cls]


# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    print("=== enum demo ===")

    print("\n--- Color ---")
    for c in Color:
        print(f"  {c.name:8s} value={c.value}  hex={c.to_hex()}")
    print(f"  Color['RED']  = {Color['RED']}")
    print(f"  Color(2)      = {Color(2)}")

    print("\n--- Priority ---")
    tasks = [(Priority.HIGH,"Task A"),(Priority.LOW,"Task B"),(Priority.MEDIUM,"Task C")]
    for p, name in sorted(tasks, key=lambda t: t[0]):
        print(f"  {p.name}: {name}")

    print("\n--- HTTPStatus ---")
    for code in [200, 404, 500]:
        s = HTTPStatus(code)
        print(f"  {s.value} {s.phrase:25s} success={s.is_success}")
    print(f"  missing (999): {HTTPStatus._missing_(999)}")

    print("\n--- Environment (StrEnum mixin) ---")
    env = Environment.PRODUCTION
    print(f"  is str: {isinstance(env, str)}")
    print(f"  == 'production': {env == 'production'}")
    print(f"  .upper(): {env.upper()}")
    print(f"  is_prod_like: {env.is_prod_like}")
    print(f"  _missing_('staging'): {Environment._missing_('staging')}")

    print("\n--- Permission (Flag) ---")
    perm = Permission.READ | Permission.WRITE
    print(f"  perm={perm}")
    print(f"  READ in perm: {Permission.READ in perm}")
    print(f"  EXEC in perm: {Permission.EXEC in perm}")
    print(f"  allows(RW): {perm.allows(Permission.RW)}")
    print(f"  from_octal(7): {Permission.from_octal(7)}")
    print(f"  RWX.to_octal(): {Permission.RWX.to_octal()}")

    print("\n--- OrderStatus (state machine) ---")
    order = OrderStatus.PENDING
    for next_s in [OrderStatus.CONFIRMED, OrderStatus.SHIPPED, OrderStatus.DELIVERED]:
        order = order.transition_to(next_s)
        print(f"  → {order.label}  terminal={order.is_terminal}")
    try:
        order.transition_to(OrderStatus.PENDING)
    except ValueError as e:
        print(f"  invalid: {e}")

    print("\n--- parse_enum ---")
    print(f"  parse_enum(Color,'RED')   = {parse_enum(Color, 'RED')}")
    print(f"  parse_enum(Color, 2)      = {parse_enum(Color, 2)}")
    print(f"  parse_enum(Color,'X')     = {parse_enum(Color, 'X')}")
    print(f"  choices: {enum_choices(Environment)}")

    print("\n=== done ===")

For the aenum alternative — aenum (PyPI; “Advanced Enumerations”) extends stdlib enum with MultiValueEnum (multiple values per member), NoAlias (allow value duplicates without aliases), extend_enum (add members to an existing enum), NamedConstant, and NamedTuple integration; Python’s stdlib enum covers the common 95% of use cases and is always available — use aenum when you need multi-value members, mixin-heavy enum hierarchies, or runtime extend_enum, stdlib enum for all standard constant, flag, and state-machine modeling. For the strenum alternative — strenum (PyPI) provides a StrEnum backport for Python versions below 3.11 where enum.StrEnum does not exist; on Python 3.11+ from enum import StrEnum is stdlib; the str, Enum mixin pattern works on all Python versions — use the str, Enum mixin or strenum backport for 3.10 and below, from enum import StrEnum on Python 3.11+. The Claude Skills 360 bundle includes enum skill sets covering Color/Priority basic enums with auto(), HTTPStatus IntEnum with property methods and missing, Environment StrEnum-style mixin, Permission/LogLevel Flag bitmask, OrderStatus state machine with transition guards, and parse_enum()/enum_choices() parsing helpers. Start with the free tier to try symbolic constants and enum state machine code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free