Enum - ChoicesΒΆ
To define a CLI parameter that can take a value from a predefined set of values you can use a standard Python enum.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)
Tip
Notice that the function parameter network
will be an Enum
, not a str
.
To get the str
value in your function's code use network.value
.
Check it:
Case insensitive Enum choicesΒΆ
You can make an Enum
(choice) CLI parameter be case-insensitive with the case_sensitive
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)
Tip
Prefer to use the Annotated
version if possible.
from enum import Enum
import typer
class NeuralNetwork(str, Enum):
simple = "simple"
conv = "conv"
lstm = "lstm"
def main(
network: NeuralNetwork = typer.Option(NeuralNetwork.simple, case_sensitive=False),
):
print(f"Training neural network of type: {network.value}")
if __name__ == "__main__":
typer.run(main)
And then the values of the Enum
will be checked no matter if lower case, upper case, or a mix:
List of Enum valuesΒΆ
A CLI parameter can also take a list of 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)
Tip
Prefer to use the Annotated
version if possible.
from enum import Enum
from typing import List
import typer
class Food(str, Enum):
food_1 = "Eggs"
food_2 = "Bacon"
food_3 = "Cheese"
def main(groceries: 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 works just like any other parameter value taking a list of things: