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.
To use an Enum as an argument in a Typer CLI application, you can define a Python Enum and use it as the type for your argument or option. Below are the key details and examples:
Enum for CLI Arguments or OptionsEnum class that lists the possible values.Enum as the type for a CLI argument or option.Here’s an example:
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)
Enum values.Enum member.Enum values are case-sensitive. You can make them case-insensitive by using typer.Option with case_sensitive=False.Example with case-insensitivity:
from typing_extensions import Annotated
import typer
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)
python main.py --help will display the available choices:
Usage: main.py [OPTIONS]
Options:
--network [simple|conv|lstm] [default: simple]
--help Show this message and exit.
Error: Invalid value for '--network': 'invalid' is not one of 'simple', 'conv', 'lstm'.
You can also allow multiple Enum values by using a List:
from typing import List
from typing_extensions import Annotated
class Food(str, Enum):
eggs = "Eggs"
bacon = "Bacon"
cheese = "Cheese"
def main(
groceries: Annotated[List[Food], typer.Option()] = [Food.eggs, Food.cheese]
):
print(f"Buying groceries: {', '.join([f.value for f in groceries])}")
if __name__ == "__main__":
typer.run(main)
This allows passing multiple values:
$ python main.py --groceries Eggs --groceries Bacon
Buying groceries: Eggs, Bacon
Enum using the functional API, ensure it subclasses both str and Enum for compatibility with Typer[2].Annotated with a custom parser function[4].