0

I'm using python 3.8.10 with typer 0.7.0 and wanting to use an enum I have defined in my project as an input argument.

I've previously used something like the following with argparse and, alongside setting choices=list(ModelTypeEnum), it's worked fine - note that this is a short example, I have many more values that in some places require the numerical values assigned.

class ModelTypeEnum(Enum):
    ALEXNET = 0
    RESNET50 = 1
    VGG19 = 2

    def __str__(self):
        return self.name

However using something like this with typer expects the argument to be an integer

app = typer.Typer()

@app.command()
def main(model_type: ModelTypeEnum = typer.Argument(..., help="Model to choose")):
    ...
    return 0
click.exceptions.BadParameter: 'RESNET50' is not one of 0, 1, 2.

While this example is short and could be converted to an (str, Enum) I would like a solution where I don't need to specify the string names manually and still have integers associated with each item - is this possible?

1 Answer 1

0

Why won't you use an approach similar to the one in this question: String-based enum in Python?

class ModelTypeEnum(str, Enum):
    ALEXNET = 'ALEXNET'
    RESNET50 = 'RESNET50'
    VGG19 = 'VGG19'

You do not need to implement __str__ method because objects of ModelTypeEnum are of both classes: str and Enum. So there is no need to introduce integer-based Enum class. It can be string from the start.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.