Make a stable public state enum
Also published in our Blogger archive.
A public state enum should give each externally visible state an explicit, durable token. Here, PublicState.PUBLISHED has the wire value "published"; the member name remains a useful Python label, while .value is the value written or accepted by the public contract. Avoid deriving public tokens from display text or relying on automatically numbered values when compatibility matters.
state_from_wire() uses the enum constructor, PublicState(value), which performs lookup by value. For the concrete input "published", it returns the canonical PUBLISHED member, confirmed by identity and value assertions. For "live", no member has that public token, so the constructor raises ValueError; the example catches that expected parse failure and prints a deterministic summary.
This establishes token stability only while future changes preserve the assigned strings. It does not provide migrations for retired values, version negotiation, or validation of the surrounding message. If an old token must stay supported, make that compatibility decision explicitly rather than silently changing a value.
The Enum API was added in Python 3.4; mixing str with Enum in this form works on modern supported Python versions. The official enum documentation documents members, .value, and constructor-based value lookup.
AI-assistance disclosure: this article was drafted with AI assistance and needs project-specific compatibility review.
from enum import Enum
class PublicState(str, Enum):
DRAFT = "draft"
PUBLISHED = "published"
ARCHIVED = "archived"
def state_from_wire(value: str) -> PublicState:
return PublicState(value)
state = state_from_wire("published")
assert state is PublicState.PUBLISHED
assert state.value == "published"
try:
state_from_wire("live")
except ValueError:
print(f"wire={state.value} invalid=live")
wire=published invalid=live