Enums in D Programming Language

Based on the provided input, here is the translated example in Python. This example maintains the educational structure and explanations, adapting them to Python’s idioms.

Enums in Python are facilitated by the enum module, which allows defining enumerated constants.

First, import the necessary modules.

from enum import Enum, auto

Our enum type ServerState has an underlying int type by default.

class ServerState(Enum):
    IDLE = auto()
    CONNECTED = auto()
    ERROR = auto()
    RETRYING = auto()

By implementing the __str__ method, values of ServerState can be printed out or converted to strings.

class ServerState(Enum):
    IDLE = auto()
    CONNECTED = auto()
    ERROR = auto()
    RETRYING = auto()
    
    def __str__(self):
        state_names = {
            ServerState.IDLE: "idle",
            ServerState.CONNECTED: "connected",
            ServerState.ERROR: "error",
            ServerState.RETRYING: "retrying"
        }
        return state_names[self]

If we have a value of type int, it cannot pass directly to the method expecting ServerState; 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(s):
    match s:
        case ServerState.IDLE:
            return ServerState.CONNECTED
        case ServerState.CONNECTED | ServerState.RETRYING:
            return ServerState.IDLE
        case ServerState.ERROR:
            return ServerState.ERROR
        case _:
            raise ValueError(f"unknown state: {s}")

if __name__ == "__main__":
    main()

To run the program, save the code into a .py file and execute it.

$ python enums.py
connected
idle

Enums in Python provide a way to represent a fixed set of related constants and ensure type safety in functions and methods by restricting the accepted values. Now that we can create and use enums in Python, let’s learn more about the language.