Enums in Python
Our enum type ServerState
has an underlying int
type.
from enum import Enum, auto
class ServerState(Enum):
Idle = auto()
Connected = auto()
Error = auto()
Retrying = auto()
The possible values for ServerState
are defined as constants. The Enum
class and auto
function generate successive constant values automatically; in this case 1, 2, 3, and so on.
By implementing the __str__
method, values of ServerState
can be printed out or converted to strings.
state_name = {
ServerState.Idle: "idle",
ServerState.Connected: "connected",
ServerState.Error: "error",
ServerState.Retrying: "retrying"
}
def server_state_to_string(state):
return state_name[state]
If we have a value of type int
, we cannot pass it to transition
- the compiler will complain about type mismatch. This provides some degree of compile-time type safety for enums.
def main():
ns = transition(ServerState.Idle)
print(ns)
ns2 = transition(ns)
print(ns2)
def transition(state):
if state == ServerState.Idle:
return ServerState.Connected
elif state in [ServerState.Connected, ServerState.Retrying]:
return ServerState.Idle
elif state == ServerState.Error:
return state
else:
raise ValueError(f"unknown state: {state}")
if __name__ == "__main__":
main()
To run the program, save the code in a file (e.g., enums.py
) and use Python to execute it.
$ python enums.py
ServerState.Connected
ServerState.Idle
The transition
function emulates a state transition for a server; it takes the existing state and returns a new state.