diff --git a/docs/tutorial/parameter-types/enum.md b/docs/tutorial/parameter-types/enum.md index 288eee5a92..52d65d0cba 100644 --- a/docs/tutorial/parameter-types/enum.md +++ b/docs/tutorial/parameter-types/enum.md @@ -153,3 +153,27 @@ Buying groceries: Eggs, Bacon ``` + + +### Functional API + +In order to use an `Enum` created using the functional API, you need to create an enum with string values. + +You also need to supply the default value as a string (not the enum): + +=== "Python 3.7+" + + ```Python hl_lines="6 10" + {!> ../docs_src/parameter_types/enum/tutorial004_an.py!} + ``` + +=== "Python 3.7+ non-Annotated" + + !!! tip + Prefer to use the `Annotated` version if possible. + + ```Python hl_lines="5 8" + {!> ../docs_src/parameter_types/enum/tutorial004.py!} + ``` + +Alternatively, you can create an `Enum` that extends both `str` and `Enum`. In Python 3.11+, there is `enum.StrEnum`. For Python 3.10 or earlier, there is the StrEnum package. diff --git a/docs_src/parameter_types/enum/tutorial004.py b/docs_src/parameter_types/enum/tutorial004.py new file mode 100644 index 0000000000..8aae98c12e --- /dev/null +++ b/docs_src/parameter_types/enum/tutorial004.py @@ -0,0 +1,13 @@ +from enum import Enum + +import typer + +NeuralNetwork = Enum("NeuralNetwork", {k: k for k in ["simple", "conv", "lstm"]}) + + +def main(network: NeuralNetwork = typer.Option("simple", case_sensitive=False)): + print(f"Training neural network of type: {network.value}") + + +if __name__ == "__main__": + typer.run(main) diff --git a/docs_src/parameter_types/enum/tutorial004_an.py b/docs_src/parameter_types/enum/tutorial004_an.py new file mode 100644 index 0000000000..a60ed650e8 --- /dev/null +++ b/docs_src/parameter_types/enum/tutorial004_an.py @@ -0,0 +1,16 @@ +from enum import Enum + +import typer +from typing_extensions import Annotated + +NeuralNetwork = Enum("NeuralNetwork", {k: k for k in ["simple", "conv", "lstm"]}) + + +def main( + network: Annotated[NeuralNetwork, typer.Option(case_sensitive=False)] = "simple", +): + print(f"Training neural network of type: {network.value}") + + +if __name__ == "__main__": + typer.run(main)