[Python] Casting int to valid enum member causes ValueError in Python

Discussão em 'Python' iniciado por Stack, Julho 25, 2025.

  1. Stack

    Stack Membro Participativo

    **Hi.

    Coming from a C# background and relatively new to python, I'm struggling with something that should be pretty straightforward (I think).

    I have an enum declared as follows:

    from enum import Enum

    class MessageRole(Enum):
    SYSTEM = 1,
    ASSISTANT = 2,
    USER = 3,
    FUNCTION = 4,
    TOOL = 5


    I'm trying to cast an integer to a specific enum value using the following code:

    role: MessageRole = MessageRole(1)


    ...which produces the following error:

    An error occurred: 1 is not a valid MessageRole


    I'm running Python 3.12.10 in VS Code.

    What am I doing wrong?

    Continue reading...

Compartilhe esta Página