Question

I have a string variable named status in my code that can take on three values "Starting", "In-progress", and "Complete". A friend of mine said it was good practice to enforce that status has one of those three values by using an enum. What is the best practice way to do this? (And for what it's worth, is an enum the right tool to use here?)

I've tried :

class Status(Enum):
    Starting = "Starting"
    InProgress = "In-progress"
    Complete = "Complete"

and then in my code I have assert statements as so:

assert(status in Status._value2member_map_)

Is this the right way to do it, or is there something else better?

Was it helpful?

Solution

Change your code to use the enum throughout - this is a prime example of where enums shine. If you continue to use a string, you'll have validations strewn throughout your code (which is a Bad Thing), and if you ever add a new status it will be a pain to update everything.

If this value is entered by the user (not likely in this scenario given the connotation, but useful in others), then take the string input from the user and convert it to the enum as soon as possible. That way you still use the enum throughout the domain-specific code and the only reference to the status as a string is in the UI layer.

OTHER TIPS

Does your code accept strings, and do you just want to make sure those strings are valid as enums? Or does your code only accept enums, and a string would be an error?

To check if an enum is acceptable:

def some_func(enum_choice):
    if enum_choice not in Status:
        raise ValueError('%r is not valid; possible choices: %r' %
                (enum_choice, list(Status)
                )

If you want to support strings as well as enums:

def some_func(choice):
    try:
        choice = Status(choice)
    except ValueError:
        # more informative error message
        raise ValueError('%r is not valid; possible choices: %r' %
                (enum_choice, list(Status)
                )
Licensed under: CC-BY-SA with attribution
scroll top