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?

sophros
  • 14,672
  • 11
  • 46
  • 75
AdmiralJonB
  • 2,038
  • 3
  • 23
  • 27

1 Answers1

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.

sophros
  • 14,672
  • 11
  • 46
  • 75