Skip to content
Myr

:memo: Add docs for Callbacks and One or Multiple commands, with docs, tests, 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 13819bf, 6ccdbb8 · Browse files · 17 files+585 added−12 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+585 added−12 removed

  • tests:+212 added−0 removed
  • other:+373 added−12 removed

17 files+585 added−12 removed

added:docs/src/commands/callback/tutorial001.py+36 added
1import typer23app = typer.Typer()4state = {"verbose": False}567@app.command()8def create(username: str):9 if state["verbose"]:10 typer.echo("About to create a user")11 typer.echo(f"Creating user: {username}")12 if state["verbose"]:13 typer.echo("Just created a user")141516@app.command()17def delete(username: str):18 if state["verbose"]:19 typer.echo("About to delete a user")20 typer.echo(f"Deleting user: {username}")21 if state["verbose"]:22 typer.echo("Just deleted a user")232425@app.callback()26def main(verbose: bool = False):27 """28 Manage users in the awesome CLI app.29 """30 if verbose:31 typer.echo("Will write verbose output")32 state["verbose"] = True333435if __name__ == "__main__":36 app()
added:docs/src/commands/callback/tutorial002.py+17 added
1import typer234def callback():5 typer.echo("Running a command")678app = typer.Typer(callback=callback)91011@app.command()12def create(name: str):13 typer.echo(f"Creating user: {name}")141516if __name__ == "__main__":17 app()
added:docs/src/commands/callback/tutorial003.py+22 added
1import typer234def callback():5 typer.echo("Running a command")678app = typer.Typer(callback=callback)91011@app.callback()12def new_callback():13 typer.echo("Override callback, running a command")141516@app.command()17def create(name: str):18 typer.echo(f"Creating user: {name}")192021if __name__ == "__main__":22 app()
added:docs/src/commands/callback/tutorial004.py+23 added
1import typer23app = typer.Typer()456@app.callback()7def callback():8 """9 Manage users CLI app.1011 Use it with the create command.12 13 A new user with the given NAME will be created.14 """151617@app.command()18def create(name: str):19 typer.echo(f"Creating user: {name}")202122if __name__ == "__main__":23 app()
added:docs/src/commands/one_or_multiple/tutorial001.py+17 added
1import typer23app = typer.Typer()456@app.command()7def create():8 typer.echo("Creating user: Hiro Hamada")91011@app.callback()12def callback():13 pass141516if __name__ == "__main__":17 app()
added:docs/src/commands/one_or_multiple/tutorial002.py+21 added
1import typer23app = typer.Typer()456@app.command()7def create():8 typer.echo("Creating user: Hiro Hamada")91011@app.callback()12def callback():13 """14 Creates a single user Hiro Hamada.1516 In the next version it will create 5 users more.17 """181920if __name__ == "__main__":21 app()
added:docs/tutorial/commands/callback.md+164 added
1When you create an `app = typer.Typer()` it works as a group of commands.23And you can create multiple commands with it.45Each of those commands can have their own *CLI parameters*.67But as those *CLI parameters* are handled by each of those commands, they don't allow us to create *CLI parameters* for the main CLI application itself.89But we can use `@app.callback()` for that.1011It's very similar to `@app.command()`, but it declares the *CLI parameters* for the main CLI application (before the commands):1213```Python hl_lines="25 26 27 28 29 30 31 32"14{!./src/commands/callback/tutorial001.py!}15```1617Here we create a `callback` with a `--verbose` *CLI option*.1819!!! tip20 After getting the `--verbose` flag, we modify a global `state`, and we use it in the other commands.2122 There are other ways to achieve the same, but this will suffice for this example.2324And as we added a docstring to the callback function, by default it will be extracted and used as the help text.2526Check it:2728<div class="termy">2930```console31// Check the help32$ python main.py --help3334// Notice the main help text, extracted from the callback function: "Manage users in the awesome CLI app."35Usage: main.py [OPTIONS] COMMAND [ARGS]...3637 Manage users in the awesome CLI app.3839Options:40 --verbose / --no-verbose41 --install-completion Install completion for the current shell.42 --show-completion Show completion for the current shell, to copy it or customize the installation.43 --help Show this message and exit.4445Commands:46 create47 delete4849// Check the new top level CLI option --verbose5051// Try it normally52$ python main.py create Camila5354Creating user: Camila5556// And now with --verbose57$ python main.py --verbose create Camila5859Will write verbose output60About to create a user61Creating user: Camila62Just created a user6364// Notice that --verbose belongs to the callback, it has to go before create or delete ⛔️65$ python main.py create --verbose Camila6667Usage: main.py create [OPTIONS] USERNAME68Try "main.py create --help" for help.6970Error: no such option: --verbose71```7273</div>7475## Adding a callback on creation7677It's also possible to add a callback when creating the `typer.Typer()` app:7879```Python hl_lines="4 5 8"80{!./src/commands/callback/tutorial002.py!}81```8283That achieves the same as with `@app.callback()`.8485Check it:8687<div class="termy">8889```console90$ python main.py create Camila9192Running a command93Creating user: Camila94```9596</div>9798## Overriding a callback99100If you added a callback when creating the `typer.Typer()` app, it's possible to override it with `@app.callback()`:101102```Python hl_lines="11 12 13"103{!./src/commands/callback/tutorial003.py!}104```105106Now `new_callback()` will be the one used.107108Check it:109110<div class="termy">111112```console113$ python main.py create Camila114115// Notice that the message is the one from new_callback()116Override callback, running a command117Creating user: Camila118```119120</div>121122## Adding a callback only for documentation123124You can also add a callback just to add the documentation in the docstring.125126It can be convenient especially if you have several lines of text, as the indentation will be automatically handled for you:127128```Python hl_lines="8 9 10 11 12 13 14 15 16"129{!./src/commands/callback/tutorial004.py!}130```131132Now the callback will be used mainly to extract the docstring for the help text.133134Check it:135136<div class="termy">137138```console139$ python main.py --help140141// Notice all the help text extracted from the callback docstring142Usage: main.py [OPTIONS] COMMAND [ARGS]...143144 Manage users CLI app.145146 Use it with the create command.147148 A new user with the given NAME will be created.149150Options:151 --install-completion Install completion for the current shell.152 --show-completion Show completion for the current shell, to copy it or customize the installation.153 --help Show this message and exit.154155Commands:156 create157158// And it just works as normally159$ python main.py create Camila160161Creating user: Camila162```163164</div>
modified:docs/tutorial/commands/one-or-multiple.md+72 added-12 removed
added:tests/test_tutorial/test_commands/test_callback/__init__.py
added:tests/test_tutorial/test_commands/test_callback/test_tutorial001.py+61 added
1import subprocess2from commands.callback import tutorial001 as mod34from typer.testing import CliRunner56app = mod.app78runner = CliRunner()91011def test_help():12 result = runner.invoke(app, ["--help"])13 assert result.exit_code == 014 assert "Manage users in the awesome CLI app." in result.output15 assert "--verbose / --no-verbose" in result.output161718def test_create():19 result = runner.invoke(app, ["create", "Camila"])20 assert result.exit_code == 021 assert "Creating user: Camila" in result.output222324def test_create_verbose():25 result = runner.invoke(app, ["--verbose", "create", "Camila"])26 assert result.exit_code == 027 assert "Will write verbose output" in result.output28 assert "About to create a user" in result.output29 assert "Creating user: Camila" in result.output30 assert "Just created a user" in result.output313233def test_delete():34 result = runner.invoke(app, ["delete", "Camila"])35 assert result.exit_code == 036 assert "Deleting user: Camila" in result.output373839def test_delete_verbose():40 result = runner.invoke(app, ["--verbose", "delete", "Camila"])41 assert result.exit_code == 042 assert "Will write verbose output" in result.output43 assert "About to delete a user" in result.output44 assert "Deleting user: Camila" in result.output45 assert "Just deleted a user" in result.output464748def test_wrong_verbose():49 result = runner.invoke(app, ["delete", "--verbose", "Camila"])50 assert result.exit_code != 051 assert "Error: no such option: --verbose" in result.output525354def test_script():55 result = subprocess.run(56 ["coverage", "run", mod.__file__, "--help"],57 stdout=subprocess.PIPE,58 stderr=subprocess.PIPE,59 encoding="utf-8",60 )61 assert "Usage" in result.stdout
added:tests/test_tutorial/test_commands/test_callback/test_tutorial002.py+25 added
1import subprocess2from commands.callback import tutorial002 as mod34from typer.testing import CliRunner56app = mod.app78runner = CliRunner()91011def test_app():12 result = runner.invoke(app, ["create", "Camila"])13 assert result.exit_code == 014 assert "Running a command" in result.output15 assert "Creating user: Camila" in result.output161718def test_script():19 result = subprocess.run(20 ["coverage", "run", mod.__file__, "--help"],21 stdout=subprocess.PIPE,22 stderr=subprocess.PIPE,23 encoding="utf-8",24 )25 assert "Usage" in result.stdout
added:tests/test_tutorial/test_commands/test_callback/test_tutorial003.py+30 added
1import subprocess2from commands.callback import tutorial003 as mod34from typer.testing import CliRunner56app = mod.app78runner = CliRunner()91011def test_app():12 result = runner.invoke(app, ["create", "Camila"])13 assert result.exit_code == 014 assert "Override callback, running a command" in result.output15 assert "Running a command" not in result.output16 assert "Creating user: Camila" in result.output171819def test_for_coverage():20 mod.callback()212223def test_script():24 result = subprocess.run(25 ["coverage", "run", mod.__file__, "--help"],26 stdout=subprocess.PIPE,27 stderr=subprocess.PIPE,28 encoding="utf-8",29 )30 assert "Usage" in result.stdout
added:tests/test_tutorial/test_commands/test_callback/test_tutorial004.py+32 added
1import subprocess2from commands.callback import tutorial004 as mod34from typer.testing import CliRunner56app = mod.app78runner = CliRunner()91011def test_help():12 result = runner.invoke(app, ["--help"])13 assert result.exit_code == 014 assert "Manage users CLI app." in result.output15 assert "Use it with the create command." in result.output16 assert "A new user with the given NAME will be created." in result.output171819def test_app():20 result = runner.invoke(app, ["create", "Camila"])21 assert result.exit_code == 022 assert "Creating user: Camila" in result.output232425def test_script():26 result = subprocess.run(27 ["coverage", "run", mod.__file__, "--help"],28 stdout=subprocess.PIPE,29 stderr=subprocess.PIPE,30 encoding="utf-8",31 )32 assert "Usage" in result.stdout
added:tests/test_tutorial/test_commands/test_one_or_multiple/__init__.py
added:tests/test_tutorial/test_commands/test_one_or_multiple/test_tutorial001.py+31 added
1import subprocess2from commands.one_or_multiple import tutorial001 as mod34from typer.testing import CliRunner56app = mod.app78runner = CliRunner()91011def test_help():12 result = runner.invoke(app, ["--help"])13 assert result.exit_code == 014 assert "Commands:" in result.output15 assert "create" in result.output161718def test_command():19 result = runner.invoke(app, ["create"])20 assert result.exit_code == 021 assert "Creating user: Hiro Hamada" in result.output222324def test_script():25 result = subprocess.run(26 ["coverage", "run", mod.__file__, "--help"],27 stdout=subprocess.PIPE,28 stderr=subprocess.PIPE,29 encoding="utf-8",30 )31 assert "Usage" in result.stdout
added:tests/test_tutorial/test_commands/test_one_or_multiple/test_tutorial002.py+33 added
1import subprocess2from commands.one_or_multiple import tutorial002 as mod34from typer.testing import CliRunner56app = mod.app78runner = CliRunner()91011def test_help():12 result = runner.invoke(app, ["--help"])13 assert result.exit_code == 014 assert "Creates a single user Hiro Hamada." in result.output15 assert "In the next version it will create 5 users more." in result.output16 assert "Commands:" in result.output17 assert "create" in result.output181920def test_command():21 result = runner.invoke(app, ["create"])22 assert result.exit_code == 023 assert "Creating user: Hiro Hamada" in result.output242526def test_script():27 result = subprocess.run(28 ["coverage", "run", mod.__file__, "--help"],29 stdout=subprocess.PIPE,30 stderr=subprocess.PIPE,31 encoding="utf-8",32 )33 assert "Usage" in result.stdout
modified:typer/main.py+1 added
224 unmodified lines
225 click_completion.init()226 click_install_param, click_show_param = get_install_completion_arguments()227 if (228 typer_instance.registered_callback229 or typer_instance.info.callback230 or typer_instance.registered_groups231 or len(typer_instance.registered_commands) > 1232 ):233 # Create a Group
500 unmodified lines