✨ Support `typing.Literal` to define a set of predefined choices (#429)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Zachary Blackwood · committed by GitHub · parent 2ece3e6 · Browse files · 7 files·+157 added−2 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Dan Walters <dan@walters.io>
- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
- Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
- Co-authored-by: svlandeg <svlandeg@github.com>
- Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
- Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>
Diff stats
7 files+157 added−2 removed
- tests:+92 added−0 removed
- other:+65 added−2 removed
Provenance
- Commit
6774f1d- Tree
1874591- Author
Zachary Blackwood <4040678+blackary@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
2ece3e6
7 files changed+157 added−2 removed
modified:docs/tutorial/parameter-types/enum.md+34 added
109 unmodified linesExpand all110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147109 unmodified linesExpand allBuying groceries: Eggs, Bacon```
</div>
### Literal choices
You can also use `Literal` to represent a set of possible predefined choices, without having to use an `Enum`:
{* docs_src/parameter_types/enum/tutorial004_an.py hl[6] *}
<div class="termy">
```console$ python main.py --help
// Notice the predefined values [simple|conv|lstm]Usage: main.py [OPTIONS]
Options: --network [simple|conv|lstm] [default: simple] --help Show this message and exit.
// Try it$ python main.py --network conv
Training neural network of type: conv
// Invalid value$ python main.py --network capsule
Usage: main.py [OPTIONS]Try "main.py --help" for help.
Error: Invalid value for '--network': 'capsule' is not one of 'simple', 'conv', 'lstm'.```
</div>added:docs_src/parameter_types/enum/tutorial004_an.py+12 added
1+import typer2+from typing_extensions import Annotated, Literal3+4+5+def main(6+ network: Annotated[Literal["simple", "conv", "lstm"], typer.Option()] = "simple",7+):8+ print(f"Training neural network of type: {network}")9+10+11+if __name__ == "__main__":12+ typer.run(main)added:docs_src/parameter_types/enum/tutorial004.py+10 added
1+import typer2+from typing_extensions import Literal3+4+5+def main(network: Literal["simple", "conv", "lstm"] = typer.Option("simple")):6+ print(f"Training neural network of type: {network}")7+8+9+if __name__ == "__main__":10+ typer.run(main)added:tests/test_tutorial/test_parameter_types/test_enum/test_tutorial004_an.py+46 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.parameter_types.enum import tutorial004_an as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def test_help():16+ result = runner.invoke(app, ["--help"])17+ assert result.exit_code == 018+ assert "--network [simple|conv|lstm]" in result.output.replace(" ", "")19+20+21+def test_main():22+ result = runner.invoke(app, ["--network", "conv"])23+ assert result.exit_code == 024+ assert "Training neural network of type: conv" in result.output25+26+27+def test_invalid():28+ result = runner.invoke(app, ["--network", "capsule"])29+ assert result.exit_code != 030+ assert "Invalid value for '--network'" in result.output31+ assert (32+ "invalid choice: capsule. (choose from" in result.output33+ or "'capsule' is not one of" in result.output34+ )35+ assert "simple" in result.output36+ assert "conv" in result.output37+ assert "lstm" in result.output38+39+40+def test_script():41+ result = subprocess.run(42+ [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],43+ capture_output=True,44+ encoding="utf-8",45+ )46+ assert "Usage" in result.stdoutadded:tests/test_tutorial/test_parameter_types/test_enum/test_tutorial004.py+46 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.parameter_types.enum import tutorial004 as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def test_help():16+ result = runner.invoke(app, ["--help"])17+ assert result.exit_code == 018+ assert "--network [simple|conv|lstm]" in result.output.replace(" ", "")19+20+21+def test_main():22+ result = runner.invoke(app, ["--network", "conv"])23+ assert result.exit_code == 024+ assert "Training neural network of type: conv" in result.output25+26+27+def test_invalid():28+ result = runner.invoke(app, ["--network", "capsule"])29+ assert result.exit_code != 030+ assert "Invalid value for '--network'" in result.output31+ assert (32+ "invalid choice: capsule. (choose from" in result.output33+ or "'capsule' is not one of" in result.output34+ )35+ assert "simple" in result.output36+ assert "conv" in result.output37+ assert "lstm" in result.output38+39+40+def test_script():41+ result = subprocess.run(42+ [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],43+ capture_output=True,44+ encoding="utf-8",45+ )46+ assert "Usage" in result.stdoutmodified:typer/_typing.py+3 added-1 removed
91 unmodified lines92 return type_ is Callable or get_origin(type_) is Callable93 94 95 def is_literal_type(type_: Type[Any]) -> bool:96- return Literal is not None and get_origin(type_) is Literal96+ import typing_extensions97 98+ return get_origin(type_) in (Literal, typing_extensions.Literal)99 100+101 def literal_values(type_: Type[Any]) -> Tuple[Any, ...]:102 return get_args(type_)103 104 11 unmodified linesmodified:typer/main.py+6 added-1 removed
15 unmodified lines16 17 import click18 from typer._types import TyperChoice19 20-from ._typing import get_args, get_origin, is_union20+from ._typing import get_args, get_origin, is_literal_type, is_union, literal_values21 from .completion import get_completion_inspect_parameters22 from .core import (23 DEFAULT_MARKUP_MODE,24 HAS_RICH,757 unmodified lines782 return TyperChoice(783 [item.value for item in annotation],784 case_sensitive=parameter_info.case_sensitive,785 )786+ elif is_literal_type(annotation):787+ return click.Choice(788+ literal_values(annotation),789+ case_sensitive=parameter_info.case_sensitive,790+ )791 raise RuntimeError(f"Type not yet supported: {annotation}") # pragma: no cover792 793 794 def lenient_issubclass(342 unmodified lines