Skip to content
Myr

✨ 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

7 files+157 added−2 removed

modified:docs/tutorial/parameter-types/enum.md+34 added
added:docs_src/parameter_types/enum/tutorial004_an.py+12 added
1import typer2from typing_extensions import Annotated, Literal345def main(6 network: Annotated[Literal["simple", "conv", "lstm"], typer.Option()] = "simple",7):8 print(f"Training neural network of type: {network}")91011if __name__ == "__main__":12 typer.run(main)
added:docs_src/parameter_types/enum/tutorial004.py+10 added
1import typer2from typing_extensions import Literal345def main(network: Literal["simple", "conv", "lstm"] = typer.Option("simple")):6 print(f"Training neural network of type: {network}")789if __name__ == "__main__":10 typer.run(main)
added:tests/test_tutorial/test_parameter_types/test_enum/test_tutorial004_an.py+46 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.parameter_types.enum import tutorial004_an as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_help():16 result = runner.invoke(app, ["--help"])17 assert result.exit_code == 018 assert "--network [simple|conv|lstm]" in result.output.replace(" ", "")192021def test_main():22 result = runner.invoke(app, ["--network", "conv"])23 assert result.exit_code == 024 assert "Training neural network of type: conv" in result.output252627def 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.output383940def 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.stdout
added:tests/test_tutorial/test_parameter_types/test_enum/test_tutorial004.py+46 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.parameter_types.enum import tutorial004 as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_help():16 result = runner.invoke(app, ["--help"])17 assert result.exit_code == 018 assert "--network [simple|conv|lstm]" in result.output.replace(" ", "")192021def test_main():22 result = runner.invoke(app, ["--network", "conv"])23 assert result.exit_code == 024 assert "Training neural network of type: conv" in result.output252627def 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.output383940def 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.stdout
modified:typer/_typing.py+3 added-1 removed
91 unmodified lines
92 return type_ is Callable or get_origin(type_) is Callable939495def is_literal_type(type_: Type[Any]) -> bool:96 return Literal is not None and get_origin(type_) is Literal96 import typing_extensions9798 return get_origin(type_) in (Literal, typing_extensions.Literal)99100101def literal_values(type_: Type[Any]) -> Tuple[Any, ...]:102 return get_args(type_)103104
11 unmodified lines
modified:typer/main.py+6 added-1 removed
15 unmodified lines
1617import click18from typer._types import TyperChoice1920from ._typing import get_args, get_origin, is_union20from ._typing import get_args, get_origin, is_literal_type, is_union, literal_values21from .completion import get_completion_inspect_parameters22from .core import (23 DEFAULT_MARKUP_MODE,24 HAS_RICH,
757 unmodified lines
782 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 cover792793794def lenient_issubclass(
342 unmodified lines