pythonenumscasting

Casting int to valid enum member causes ValueError in Python


**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?


Solution

  • The issue is due to the trailing commas you added in your enum value. Python sees the value with trailing commas as tuples. To resolve the issue:

    from enum import Enum
    
    
    class MessageRole(Enum):
        SYSTEM = 1
        ASSISTANT = 2
        USER = 3
        FUNCTION = 4
        TOOL = 5
    
    role: MessageRole = MessageRole(1)
    print(role)