Skip to content
Myr

:memo: Add docs for using Click with Typer (#70)

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

* :memo: Add docs for using Click with Typer * :white_check_mark: Add tests for integrating Click and Typer

authored by Sebastián Ramírez · committed by GitHub · parent 9e3553a · Browse files · 9 files+372 added−0 removed
This commit

State

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

Diff stats

9 files+372 added−0 removed

  • tests:+73 added−0 removed
  • other:+299 added−0 removed

9 files+372 added−0 removed

added:docs/src/using_click/tutorial001.py+14 added
1import click234@click.command()5@click.option("--count", default=1, help="Number of greetings.")6@click.option("--name", prompt="Your name", help="The person to greet.")7def hello(count, name):8 """Simple program that greets NAME for a total of COUNT times."""9 for x in range(count):10 click.echo("Hello %s!" % name)111213if __name__ == "__main__":14 hello()
added:docs/src/using_click/tutorial002.py+24 added
1import click234@click.group()5def cli():6 pass789@click.command()10def initdb():11 click.echo("Initialized the database")121314@click.command()15def dropdb():16 click.echo("Dropped the database")171819cli.add_command(initdb)20cli.add_command(dropdb)212223if __name__ == "__main__":24 cli()
added:docs/src/using_click/tutorial003.py+34 added
1import click2import typer34app = typer.Typer()567@app.command()8def top():9 """10 Top level command, form Typer11 """12 typer.echo("The Typer app is at the top level")131415@app.callback()16def callback():17 """18 Typer app, including Click subapp19 """202122@click.command()23@click.option("--name", prompt="Your name", help="The person to greet.")24def hello(name):25 """Simple program that greets NAME for a total of COUNT times."""26 click.echo("Hello %s!" % name)272829typer_click_object = typer.main.get_command(app)3031typer_click_object.add_command(hello, "hello")3233if __name__ == "__main__":34 typer_click_object()
added:docs/src/using_click/tutorial004.py+36 added
1import click2import typer345@click.group()6def cli():7 pass8910@cli.command()11def initdb():12 click.echo("Initialized the database")131415@cli.command()16def dropdb():17 click.echo("Dropped the database")181920app = typer.Typer()212223@app.command()24def sub():25 """26 A single-command Typer sub app27 """28 typer.echo("Typer is now below Click, the Click app is the top level")293031typer_click_object = typer.main.get_command(app)3233cli.add_command(typer_click_object, "sub")3435if __name__ == "__main__":36 cli()
added:docs/tutorial/using-click.md+190 added
1!!! warning2 This is a more advanced topic, if you are starting with **Typer**, feel free to skip it.34 It will be mostly useful for people that already work with Click and have questions around it.56**Typer** is powered by <a href="https://click.palletsprojects.com" class="external-link" target="_blank">Click</a>. It does all the work underneath.78Here is some more information related to using both together.910## A single app with both Click and **Typer**1112If you already have a Click application and want to migrate to **Typer**, or to add some Typer components, you can get a Click `Command` from your Typer application and then use Click directly.1314### How Click works1516Before knowing how to combine Click and **Typer**, let's first check a little about how Click works.1718#### Click `Command`1920Any Click application has an object of class `Command`. That's, more or less, the most basic Click object.2122A `Command` can have its own *CLI arguments* and *CLI options*, and it has a function that it calls.2324For example, in this Click app:2526```Python hl_lines="7 14"27{!./src/using_click/tutorial001.py!}28```2930The original `hello` variable is converted by Click from a function to a `Command` object. And the original `hello` function is used by that `Command` internally, but it is no longer named `hello` (as `hello` is now a Click `Command`).3132#### Click `Group`3334Then Click also has a `Group` class, it **inherits from `Command`**. So, a `Group` object is *also* a `Command`.3536A `Group` can also have its own *CLI arguments* and *CLI options*.3738A `Group` can have subcommands of class `Command` or sub groups of class `Group` as well.3940And a `Group` can also have a function that it calls, right before calling the function for any specific subcommand.4142For example:4344```Python hl_lines="5 19 20"45{!./src/using_click/tutorial002.py!}46```4748The `cli` variable is converted by Click from a function to a `Group` object. And the original `cli` function is used by that `Group` internally.4950!!! tip51 The original `cli` function would be the equivalent of a [Typer Callback](./commands/callback.md){.internal-link target=_blank}.5253Then the `cli` variable, that now is a `Group` object, is used to add sub-commands.5455### How **Typer** works5657Typer doesn't modify the functions. You create an explicit variable of class `typer.Typer` and use it to *register* those functions.5859And then, when you call the app, Typer goes and creates a Click `Command` (or `Group`), and then calls it.6061If your app only has one command, then when you call it, **Typer** creates a single Click `Command` object and calls it.6263But **Typer** creates a Click `Group` object if your app has any of:6465* More than one command.66* A callback.67* Sub-Typer apps (sub commands).6869!!! tip70 If you want to learn more about this check the section [One or Multiple Commands](./commands/one-or-multiple.md){.internal-link target=_blank}.7172### Combine Click and **Typer**7374**Typer** uses an internal function `typer.main.get_command()` to generate a Click `Command` (or `Group`) from a `typer.Typer` object.7576You can use it directly, and use the Click object with other Click applications.7778### Including a Click app in a **Typer** app7980For example, you could have a **Typer** app, generate a Click `Group` from it, and then include other Click apps in it:8182```Python hl_lines="15 16 29 31 34"83{!./src/using_click/tutorial003.py!}84```8586Notice that we add a callback that does nothing (only document the CLI program), to make sure **Typer** creates a Click `Group`. That way we can add sub-commands to that Click `Group`.8788Then we generate a Click object from our `typer.Typer` app (`typer_click_object`), and then we can include another Click object (`hello`) in this Click `Group`.8990And that way, our **Typer** app will have a subcommand `top` built with Typer, and a subcommand `hello` built with Click.9192Check it:9394<div class="termy">9596```console97$ python main.py9899// Notice we have both subcommands, top and hello100Usage: main.py [OPTIONS] COMMAND [ARGS]...101102 Typer app, including Click subapp103104Options:105 --install-completion Install completion for the current shell.106 --show-completion Show completion for the current shell, to copy it or customize the installation.107108 --help Show this message and exit.109110Commands:111 hello Simple program that greets NAME for a total of COUNT times.112 top Top level command, form Typer113114// Call the Typer part115$ python main.py top116117The Typer app is at the top level118119// Call the Click part120$ python main.py hello --name Camila121122Hello Camila!123```124125</div>126127### Including a **Typer** app in a Click app128129The same way, you can do the contrary and include a **Typer** sub app in a bigger Click app:130131```Python hl_lines="31 33 36"132{!./src/using_click/tutorial004.py!}133```134135Notice that we don't have to add a callback or more commands, we can just create a **Typer** app that generates a single Click `Command`, as we don't need to include anything under the Typer app.136137Then we generate a Click object from our `typer.Typer` app (`typer_click_object`), and then we use **the Click `cli` to include** our Click object from our Typer app.138139In this case, the original Click app includes the **Typer** app.140141And then we call the *original Click* app, not the Typer app.142143Check it:144145<div class="termy">146147```console148$ python main.py149150// We get our Typer app down there in the sub command151Usage: main.py [OPTIONS] COMMAND [ARGS]...152153Options:154 --help Show this message and exit.155156Commands:157 dropdb158 initdb159 sub A single-command Typer sub app160161162// Use the Click part163$ python main.py initdb164165Initialized the database166167// And use the Typer part168$ python main.py sub169170Typer is now below Click, the Click app is the top level171```172173</div>174175## About Click decorators176177Typer apps don't work with Click decorators directly.178179This is because **Typer** doesn't modify functions to add metadata or to convert them to another object like Click does.180181So, things like `@click.pass_context` won't work.182183Most of the functionality provided by decorators in Click has an alternative way of doing it in **Typer**.184185For example, to access the context, you can just declare a function parameter of type `typer.Context`.186187!!! tip188 You can read more about using the context in the docs: [Commands: Using the Context](./commands/using-the-context.md){.internal-link target=_blank}189190But if you need to use something based on Click decorators, you can always generate a Click object using the methods described above, and use it as you would normally use Click.
added:tests/test_tutorial/test_using_click/__init__.py
added:tests/test_tutorial/test_using_click/test_tutorial003.py+34 added
1import subprocess23from click.testing import CliRunner45from using_click import tutorial003 as mod67runner = CliRunner()8910def test_cli():11 result = runner.invoke(mod.typer_click_object, [])12 assert "Usage" in result.stdout13 assert "hello" in result.stdout14 assert "top" in result.stdout151617def test_typer():18 result = runner.invoke(mod.typer_click_object, ["top"])19 assert "The Typer app is at the top level" in result.stdout202122def test_click():23 result = runner.invoke(mod.typer_click_object, ["hello", "--name", "Camila"])24 assert "Hello Camila!" in result.stdout252627def test_script():28 result = subprocess.run(29 ["coverage", "run", mod.__file__, "--help"],30 stdout=subprocess.PIPE,31 stderr=subprocess.PIPE,32 encoding="utf-8",33 )34 assert "Usage" in result.stdout
added:tests/test_tutorial/test_using_click/test_tutorial004.py+39 added
1import subprocess23from click.testing import CliRunner45from using_click import tutorial004 as mod67runner = CliRunner()8910def test_cli():11 result = runner.invoke(mod.cli, [])12 assert "Usage" in result.stdout13 assert "dropdb" in result.stdout14 assert "sub" in result.stdout151617def test_typer():18 result = runner.invoke(mod.cli, ["sub"])19 assert "Typer is now below Click, the Click app is the top level" in result.stdout202122def test_click_initdb():23 result = runner.invoke(mod.cli, ["initdb"])24 assert "Initialized the database" in result.stdout252627def test_click_dropdb():28 result = runner.invoke(mod.cli, ["dropdb"])29 assert "Dropped the database" in result.stdout303132def test_script():33 result = subprocess.run(34 ["coverage", "run", mod.__file__, "--help"],35 stdout=subprocess.PIPE,36 stderr=subprocess.PIPE,37 encoding="utf-8",38 )39 assert "Usage" in result.stdout
modified:mkdocs.yml+1 added