Python Basics: Giving Choices Names with enum
A job status has a small set of allowed choices. An enumeration gives each choice a name and value, so code can use Status.READY consistently.
Use Python 3.12 or newer on Linux. Each example is independent, uses in-memory data, and needs no network access.
Define and look up members
Save as demo_enum_1.py:
from enum import Enum
class Status(Enum):
READY = "ready"
RUNNING = "running"
DONE = "done"
status = Status("ready")
print(status)
print("Name:", status.name)
print("Value:", status.value)
print("Same member:", status is Status["READY"])
print("Equals text:", status == "ready")Run it from the directory where you saved it:
python3 demo_enum_1.pyOutput:
Status.READY
Name: READY
Value: ready
Same member: True
Equals text: FalseParentheses look up a member by value; square brackets look it up by name. A plain Enum member is distinct from its string value. Compare members to members, or explicitly use .value when you need the stored text.
Reject an unknown value
Save as demo_enum_2.py:
from enum import Enum
class Status(Enum):
READY = "ready"
DONE = "done"
for raw in ("ready", "DONE", "done", "paused"):
try:
status = Status(raw)
except ValueError:
print(f"{raw}: invalid status")
else:
print(f"{raw}: {status.name}")Run it from the directory where you saved it:
python3 demo_enum_2.pyOutput:
ready: READY
DONE: invalid status
done: DONE
paused: invalid statusValue lookup is case-sensitive by default. Convert incoming text where it enters your program, and handle ValueError there. Unknown name lookup, such as Status["PAUSED"], raises KeyError instead. Defining an enum does not automatically validate unrelated string variables.
Use string-compatible choices
Save as demo_enum_3.py:
from enum import StrEnum, auto, unique
@unique
class Format(StrEnum):
TEXT = auto()
JSON = auto()
for member in Format:
print(member.name, member.value)
print("As text:", str(Format.JSON))
print("Equals text:", Format.JSON == "json")
print("Uppercase:", Format.JSON.upper())Run it from the directory where you saved it:
python3 demo_enum_3.pyOutput:
TEXT text
JSON json
As text: json
Equals text: True
Uppercase: JSONStrEnum members are also strings. Here, auto() creates lowercase values from the names. String operations return ordinary strings. Some APIs require an exact str, so convert with str(member) when needed.
Duplicate enum values normally create aliases. @unique rejects them when the class is created. Use explicit values instead of auto() when stored data must keep working after a member is renamed.
References
Acknowledgements
This post was created with assistance from AI.