typer enum argument
- User
typer enum argument
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
typer enum argument
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Typer allows you to easily define command-line arguments and options that accept only a predefined set of values using Python's standard enum.Enum class. This provides type safety, validation, and improved help documentation for your CLI applications.
To create an argument or option that accepts only specific values, you can define an enum class that inherits from both str and Enum:
from enum import Enum
import typer
class NeuralNetwork(str, Enum):
simple = "simple"
conv = "conv"
lstm = "lstm"
def main(network: NeuralNetwork = NeuralNetwork.simple):
print(f"Training neural network of type: {network.value}")
if __name__ == "__main__":
typer.run(main)
This creates a CLI application that accepts a --network option with three possible values: simple, conv, or lstm[1].
When you run the help command for this application, Typer automatically shows the available choices:
$ python main.py --help
Usage: main.py [OPTIONS]
Options:
--network [simple|conv|lstm] [default: simple]
--help Show this message and exit.
It's important to note that the function parameter (in this case network) will be an Enum object, not a string. To get the string value in your function's code, use network.value[1].
By default, enum choices are case-sensitive. If you try to use a value with different casing than defined, you'll get an error:
$ python main.py --network CONV
Error: Invalid value for '--network': 'CONV' is not one of 'simple', 'conv', 'lstm'.
You can make enum choices case-insensitive by using the case_sensitive=False parameter:
from enum import Enum
import typer
from typing_extensions import Annotated
class NeuralNetwork(str, Enum):
simple = "simple"
conv = "conv"
lstm = "lstm"
def main(
network: Annotated[
NeuralNetwork, typer.Option(case_sensitive=False)
] = NeuralNetwork.simple,
):
print(f"Training neural network of type: {network.value}")
if __name__ == "__main__":
typer.run(main)
With this change, users can input values with any casing:
$ python main.py --network CONV
Training neural network of type: conv
$ python main.py --network LsTm
Training neural network of type: lstm
```[1]
## Using Enums as Arguments (Not Just Options)
The examples above show enums used with options, but you can also use them with arguments by using `typer.Argument()`:
```python
def main(
network: Annotated[NeuralNetwork, typer.Argument()] = NeuralNetwork.simple
):
print(f"Training neural network of type: {network.value}")
You can also create a parameter that accepts multiple enum values:
from enum import Enum
from typing import List
import typer
from typing_extensions import Annotated
class Food(str, Enum):
food_1 = "Eggs"
food_2 = "Bacon"
food_3 = "Cheese"
def main(groceries: Annotated[List[Food], typer.Option()] = [Food.food_1, Food.food_3]):
print(f"Buying groceries: {', '.join([f.value for f in groceries])}")
if __name__ == "__main__":
typer.run(main)
This allows users to specify multiple values:
$ python main.py --groceries "Eggs" --groceries "Bacon"
Buying groceries: Eggs, Bacon
```[1]
## Integer-Based Enums
If you need to use enums with integer values but still want to allow users to input string identifiers, you may encounter some challenges. The standard approach of inheriting from both `str` and `Enum` doesn't work well with integer values.
For integer-based enums, a common workaround is to use `typer.Option` with a custom parser or to structure your enum differently:
```python
class ModelTypeEnum(Enum):
ALEXNET = 0
RESNET50 = 1
VGG19 = 2
def __str__(self):
return self.name
With Typer, you would typically convert this to a string-based enum:
class ModelTypeEnum(str, Enum):
ALEXNET = "ALEXNET"
RESNET50 = "RESNET50"
VGG19 = "VGG19"
```[3]
## Functional API Workaround
When using the functional API to create enums, you might need to provide a workaround:
```python
# If this doesn't work:
def main(network: my_enum_created_functionally = default_enum_value):
...
# Try this instead:
def main(network = typer.Option(default_enum_value)):
...
```[2]
## Adding Help Text for Enum Choices
You can enhance your CLI's usability by adding help text to explain what each enum value means:
```python
def main(
network: Annotated[
NeuralNetwork,
typer.Argument(help="Type of neural network architecture to use")
] = NeuralNetwork.simple
):
print(f"Training neural network of type: {network.value}")
```[7]
By leveraging Python's enum module with Typer, you can create more robust and user-friendly command-line interfaces with validated input choices and helpful documentation.