Skip to content
Myr

:memo: :sparkles: :bug: Add docs for CLI parameters with multiple values, with tests and bug fixes

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Sebastián Ramírez · committed by GitHub · parents ff37cb8, c84fcae · Browse files · 17 files+417 added−5 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

17 files+417 added−5 removed

  • tests:+155 added−0 removed
  • other:+262 added−5 removed

17 files+417 added−5 removed

added:docs/src/multiple_values/arguments_with_multiple_values/tutorial001.py+15 added
1from pathlib import Path2from typing import List34import typer567def main(files: List[Path], celebration: str):8 for path in files:9 if path.is_file():10 typer.echo(f"This file exists: {path.name}")11 typer.echo(celebration)121314if __name__ == "__main__":15 typer.run(main)
added:docs/src/multiple_values/multiple_options/tutorial001.py+15 added
1from typing import List23import typer456def main(user: List[str] = typer.Option(None)):7 if not user:8 typer.echo("No provided users")9 raise typer.Abort()10 for u in user:11 typer.echo(f"Processing user: {u}")121314if __name__ == "__main__":15 typer.run(main)
added:docs/src/multiple_values/multiple_options/tutorial002.py+11 added
1from typing import List23import typer456def main(number: List[float] = typer.Option([])):7 typer.echo(f"The sum is {sum(number)}")8910if __name__ == "__main__":11 typer.run(main)
added:docs/src/multiple_values/options_with_multiple_values/tutorial001.py+17 added
1from typing import Tuple23import typer456def main(user: Tuple[str, int, bool] = typer.Option((None, None, None))):7 username, coins, is_wizard = user8 if not username:9 typer.echo("No user provided")10 raise typer.Abort()11 typer.echo(f"The username {username} has {coins} coins")12 if is_wizard:13 typer.echo("And this user is a wizard!")141516if __name__ == "__main__":17 typer.run(main)
added:docs/tutorial/multiple-values/arguments-with-multiple-values.md+28 added
added:docs/tutorial/multiple-values/index.md+3 added
added:docs/tutorial/multiple-values/multiple-options.md+66 added
added:docs/tutorial/multiple-values/options-with-multiple-values.md+92 added
1You can also declare a *CLI option* that takes several values of different types.23You can set the number of values and types to anything you want, but it has to be a fixed number of values.45For this, use the standard Python `typing.Tuple`:67```Python hl_lines="1 6"8{!./src/multiple_values/options_with_multiple_values/tutorial001.py!}9```1011Each of the internal types defines the type of each value in the tuple.1213So:1415```Python16user: Tuple[str, int, bool]17```1819means that the parameter `user` is a tuple of 3 values.2021* The first value is a `str`.22* The second value is an `int`.23* The third value is a `bool`.2425Later we do:2627```Python28username, coins, is_wizard = user29```3031If you hadn't seen that, it means that `user` is a tuple with 3 values, and we are assigning each of the values to a new variable:3233* The first value in the tuple `user` (a `str`) goes to the variable `username`.34* The second value in the tuple `user` (an `int`) goes to the variable `coins`.35* The third value in the tuple `user` (a `bool`) goes to the variable `is_wizard`.3637So, this:3839```Python40username, coins, is_wizard = user41```4243is equivalent to this:4445```Python46username = user[0]47coins = user[1]48is_wizard = user[2]49```5051!!! tip52 Notice that the default is a tuple with `(None, None, None)`.5354 You cannot simply use `None` here as the default because <a href="https://github.com/pallets/click/issues/472" target="_blank">Click doesn't support it</a>.5556## Check it5758Now let's see how this works in the terminal:5960<div class="termy">6162```console63// check the help64$ python main.py --help6566// Notice the &lt;TEXT INTEGER BOOLEAN&gt;67Usage: main.py [OPTIONS]6869Options:70 --user &lt;TEXT INTEGER BOOLEAN&gt;...71 --install-completion Install completion for the current shell.72 --show-completion Show completion for the current shell, to copy it or customize the installation.73 --help Show this message and exit.7475// Now try it76$ python main.py --user Camila 50 yes7778The username Camila has 50 coins79And this user is a wizard!8081// With other values82$ python main.py --user Morty 3 no8384The username Morty has 3 coins8586// Try with invalid values (not enough)87$ python main.py --user Camila 508889Error: --user option requires 3 arguments90```9192</div>
added:tests/test_tutorial/test_multiple_values/test_arguments_with_multiple_values/__init__.py
added:tests/test_tutorial/test_multiple_values/test_arguments_with_multiple_values/test_tutorial001.py+27 added
1import subprocess23import typer4from typer.testing import CliRunner56from multiple_values.arguments_with_multiple_values import tutorial001 as mod78runner = CliRunner()9app = typer.Typer()10app.command()(mod.main)111213def test_main():14 result = runner.invoke(app, ["README.md", "pyproject.toml", "woohoo!"])15 assert result.exit_code == 016 assert "This file exists: README.md\nwoohoo!" in result.output17 assert "This file exists: pyproject.toml\nwoohoo!" in result.output181920def test_script():21 result = subprocess.run(22 ["coverage", "run", mod.__file__, "--help"],23 stdout=subprocess.PIPE,24 stderr=subprocess.PIPE,25 encoding="utf-8",26 )27 assert "Usage" in result.stdout
added:tests/test_tutorial/test_multiple_values/test_multiple_options/__init__.py
added:tests/test_tutorial/test_multiple_values/test_multiple_options/test_tutorial001.py+43 added
1import subprocess23import typer4from typer.testing import CliRunner56from multiple_values.multiple_options import tutorial001 as mod78runner = CliRunner()9app = typer.Typer()10app.command()(mod.main)111213def test_main():14 result = runner.invoke(app)15 assert result.exit_code != 016 assert "No provided users" in result.output17 assert "Aborted!" in result.output181920def test_1_user():21 result = runner.invoke(app, ["--user", "Camila"])22 assert result.exit_code == 023 assert "Processing user: Camila" in result.output242526def test_3_user():27 result = runner.invoke(28 app, ["--user", "Camila", "--user", "Rick", "--user", "Morty"]29 )30 assert result.exit_code == 031 assert "Processing user: Camila" in result.output32 assert "Processing user: Rick" in result.output33 assert "Processing user: Morty" in result.output343536def test_script():37 result = subprocess.run(38 ["coverage", "run", mod.__file__, "--help"],39 stdout=subprocess.PIPE,40 stderr=subprocess.PIPE,41 encoding="utf-8",42 )43 assert "Usage" in result.stdout
added:tests/test_tutorial/test_multiple_values/test_multiple_options/test_tutorial002.py+38 added
1import subprocess23import typer4from typer.testing import CliRunner56from multiple_values.multiple_options import tutorial002 as mod78runner = CliRunner()9app = typer.Typer()10app.command()(mod.main)111213def test_main():14 result = runner.invoke(app)15 assert result.exit_code == 016 assert "The sum is 0" in result.output171819def test_1_number():20 result = runner.invoke(app, ["--number", "2"])21 assert result.exit_code == 022 assert "The sum is 2.0" in result.output232425def test_2_number():26 result = runner.invoke(app, ["--number", "2", "--number", "3", "--number", "4.5"])27 assert result.exit_code == 028 assert "The sum is 9.5" in result.output293031def test_script():32 result = subprocess.run(33 ["coverage", "run", mod.__file__, "--help"],34 stdout=subprocess.PIPE,35 stderr=subprocess.PIPE,36 encoding="utf-8",37 )38 assert "Usage" in result.stdout
added:tests/test_tutorial/test_multiple_values/test_options_with_multiple_values/__init__.py
added:tests/test_tutorial/test_multiple_values/test_options_with_multiple_values/test_tutorial001.py+47 added
1import subprocess23import typer4from typer.testing import CliRunner56from multiple_values.options_with_multiple_values import tutorial001 as mod78runner = CliRunner()9app = typer.Typer()10app.command()(mod.main)111213def test_main():14 result = runner.invoke(app)15 assert result.exit_code != 016 assert "No user provided" in result.output17 assert "Aborted!" in result.output181920def test_user_1():21 result = runner.invoke(app, ["--user", "Camila", "50", "yes"])22 assert result.exit_code == 023 assert "The username Camila has 50 coins" in result.output24 assert "And this user is a wizard!" in result.output252627def test_user_2():28 result = runner.invoke(app, ["--user", "Morty", "3", "no"])29 assert result.exit_code == 030 assert "The username Morty has 3 coins" in result.output31 assert "And this user is a wizard!" not in result.output323334def test_invalid_user():35 result = runner.invoke(app, ["--user", "Camila", "50"])36 assert result.exit_code != 037 assert "Error: --user option requires 3 arguments" in result.output383940def test_script():41 result = subprocess.run(42 ["coverage", "run", mod.__file__, "--help"],43 stdout=subprocess.PIPE,44 stderr=subprocess.PIPE,45 encoding="utf-8",46 )47 assert "Usage" in result.stdout
added:tests/test_tutorial/test_multiple_values/__init__.py
modified:typer/main.py+15 added-5 removed
460 unmodified lines
461462 return convertor463464465def generate_iter_convertor(convertor: Callable[[Any], Any]) -> Callable:466 def internal_convertor(value: Any) -> List[Any]:467 return [convertor(v) for v in value]468469 return internal_convertor470471472def get_callback(473 *,474 callback: Optional[Callable] = None,475 params: Sequence[click.Parameter] = [],
160 unmodified lines
636 origin = getattr(main_type, "__origin__", None)637 # Handle Tuples and Lists638 if lenient_issubclass(origin, List):639 main_type = main_type.__args__[0]633 assert (634 "__origin__" not in main_type640 assert not getattr(641 main_type, "__origin__", None642 ), "List types with complex sub-types are not currently supported"643 is_list = True644 elif lenient_issubclass(origin, Tuple): # type: ignore645 types = []639 for type_ in origin.__args__:640 assert (641 "__origin__" not in type_646 for type_ in main_type.__args__:647 assert not getattr(648 type_, "__origin__", None649 ), "Tuple types with complex sub-types are not currently supported"650 types.append(651 get_click_type(annotation=type_, parameter_info=parameter_info)652 )
6 unmodified lines
659 if lenient_issubclass(main_type, Path):660 convertor = param_path_convertor661 if lenient_issubclass(main_type, Enum):662 convertor = generate_enum_convertor(main_type)663 if convertor and is_list:664 convertor = generate_iter_convertor(convertor)665 # TODO: handle recursive conversion for tuples666 if isinstance(parameter_info, OptionInfo):667 if main_type is bool and not (parameter_info.is_flag is False):668 is_flag = True669 # Click doesn't accept a flag of type bool, only None, and then it sets it
74 unmodified lines