[Python] How can a Python enum accept any value without raising ValueError

Discussão em 'Python' iniciado por Stack, Agosto 9, 2025.

  1. Stack

    Stack Membro Participativo

    Suppose I am implementing a network service that receives commands. I want to have an enumeration of these commands, so I can write something like:

    class Command(enum.Enum):
    ECHO = 0x01
    LOGIN = 0x02
    SEND_FILE = 0x03

    def handle_packet(p: bytes):
    command = Command(p[0])
    if command == Command.ECHO:
    print(p[1:])
    elif ...
    elif ...
    else:
    print('Ignoring unknown command', command)


    If the client supports a newer version of this protocol than my server, they might send a command that I don't have listed in my enum. For example, if the client sends me 0x04, the constructor Command(p[0]) will throw a ValueError.

    Instead, I'd like command = Command(0x04) to create an instance where command.value = 4 and it has a name generated on-the-fly like COMMAND_04.

    Continue reading...

Compartilhe esta Página