Enums in Python
Our enum type ServerState
has an underlying int
type.
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.
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.
To run the program, save the code in a file (e.g., enums.py
) and use Python to execute it.
The transition
function emulates a state transition for a server; it takes the existing state and returns a new state.