Use a literal-like enum to make command states explicit
A StrEnum gives a small command-state vocabulary named members and string values. The example defines QUEUED, RUNNING, and DONE, then constructs a state from the input string "running". Looking it up returns the corresponding member, so can_cancel can compare explicit states rather than relying on unrelated spellings scattered through the program.
The assertions show the chosen transition policy: queued and running commands are cancellable, while done commands are not. They also show that str(state) is the value "running", which is useful when an existing interface expects a string. An unknown value such as CommandState("paused") raises ValueError; decide whether to handle that error at an input boundary or represent an explicit fallback state.
This is literal-like, not runtime type enforcement. Python will not automatically prevent a caller from passing a plain string to can_cancel; annotations help static tooling, while runtime checks remain application code. String operations on a StrEnum member produce ordinary strings rather than enum members. StrEnum was added in Python 3.11. See the official StrEnum documentation and Enum member-value reference.
AI assistance disclosure: this article was drafted with AI assistance and should be adapted to the application’s own data rules.
from enum import StrEnum
class CommandState(StrEnum):
QUEUED = "queued"
RUNNING = "running"
DONE = "done"
def can_cancel(state: CommandState) -> bool:
return state in {CommandState.QUEUED, CommandState.RUNNING}
state = CommandState("running")
assert state is CommandState.RUNNING
assert can_cancel(state) is True
assert can_cancel(CommandState.DONE) is False
assert str(state) == "running"
print(f"{state.name}:{state}")
RUNNING:running
Comments
Post a Comment