: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
Provenance
- Commit
48698ff- Tree
605fb80- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
9e3553a
9 files changed+372 added−0 removed
added:docs/src/using_click/tutorial001.py+14 added
1+import click2+3+4+@click.command()5+@click.option("--count", default=1, help="Number of greetings.")6+@click.option("--name", prompt="Your name", help="The person to greet.")7+def 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)11+12+13+if __name__ == "__main__":14+ hello()added:docs/src/using_click/tutorial002.py+24 added
1+import click2+3+4+@click.group()5+def cli():6+ pass7+8+9+@click.command()10+def initdb():11+ click.echo("Initialized the database")12+13+14+@click.command()15+def dropdb():16+ click.echo("Dropped the database")17+18+19+cli.add_command(initdb)20+cli.add_command(dropdb)21+22+23+if __name__ == "__main__":24+ cli()added:docs/src/using_click/tutorial003.py+34 added
1+import click2+import typer3+4+app = typer.Typer()5+6+7+@app.command()8+def top():9+ """10+ Top level command, form Typer11+ """12+ typer.echo("The Typer app is at the top level")13+14+15+@app.callback()16+def callback():17+ """18+ Typer app, including Click subapp19+ """20+21+22+@click.command()23+@click.option("--name", prompt="Your name", help="The person to greet.")24+def hello(name):25+ """Simple program that greets NAME for a total of COUNT times."""26+ click.echo("Hello %s!" % name)27+28+29+typer_click_object = typer.main.get_command(app)30+31+typer_click_object.add_command(hello, "hello")32+33+if __name__ == "__main__":34+ typer_click_object()added:docs/src/using_click/tutorial004.py+36 added
1+import click2+import typer3+4+5+@click.group()6+def cli():7+ pass8+9+10+@cli.command()11+def initdb():12+ click.echo("Initialized the database")13+14+15+@cli.command()16+def dropdb():17+ click.echo("Dropped the database")18+19+20+app = typer.Typer()21+22+23+@app.command()24+def sub():25+ """26+ A single-command Typer sub app27+ """28+ typer.echo("Typer is now below Click, the Click app is the top level")29+30+31+typer_click_object = typer.main.get_command(app)32+33+cli.add_command(typer_click_object, "sub")34+35+if __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.3+4+ It will be mostly useful for people that already work with Click and have questions around it.5+6+**Typer** is powered by <a href="https://click.palletsprojects.com" class="external-link" target="_blank">Click</a>. It does all the work underneath.7+8+Here is some more information related to using both together.9+10+## A single app with both Click and **Typer**11+12+If 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.13+14+### How Click works15+16+Before knowing how to combine Click and **Typer**, let's first check a little about how Click works.17+18+#### Click `Command`19+20+Any Click application has an object of class `Command`. That's, more or less, the most basic Click object.21+22+A `Command` can have its own *CLI arguments* and *CLI options*, and it has a function that it calls.23+24+For example, in this Click app:25+26+```Python hl_lines="7 14"27+{!./src/using_click/tutorial001.py!}28+```29+30+The 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`).31+32+#### Click `Group`33+34+Then Click also has a `Group` class, it **inherits from `Command`**. So, a `Group` object is *also* a `Command`.35+36+A `Group` can also have its own *CLI arguments* and *CLI options*.37+38+A `Group` can have subcommands of class `Command` or sub groups of class `Group` as well.39+40+And a `Group` can also have a function that it calls, right before calling the function for any specific subcommand.41+42+For example:43+44+```Python hl_lines="5 19 20"45+{!./src/using_click/tutorial002.py!}46+```47+48+The `cli` variable is converted by Click from a function to a `Group` object. And the original `cli` function is used by that `Group` internally.49+50+!!! tip51+ The original `cli` function would be the equivalent of a [Typer Callback](./commands/callback.md){.internal-link target=_blank}.52+53+Then the `cli` variable, that now is a `Group` object, is used to add sub-commands.54+55+### How **Typer** works56+57+Typer doesn't modify the functions. You create an explicit variable of class `typer.Typer` and use it to *register* those functions.58+59+And then, when you call the app, Typer goes and creates a Click `Command` (or `Group`), and then calls it.60+61+If your app only has one command, then when you call it, **Typer** creates a single Click `Command` object and calls it.62+63+But **Typer** creates a Click `Group` object if your app has any of:64+65+* More than one command.66+* A callback.67+* Sub-Typer apps (sub commands).68+69+!!! 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}.71+72+### Combine Click and **Typer**73+74+**Typer** uses an internal function `typer.main.get_command()` to generate a Click `Command` (or `Group`) from a `typer.Typer` object.75+76+You can use it directly, and use the Click object with other Click applications.77+78+### Including a Click app in a **Typer** app79+80+For example, you could have a **Typer** app, generate a Click `Group` from it, and then include other Click apps in it:81+82+```Python hl_lines="15 16 29 31 34"83+{!./src/using_click/tutorial003.py!}84+```85+86+Notice 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`.87+88+Then 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`.89+90+And that way, our **Typer** app will have a subcommand `top` built with Typer, and a subcommand `hello` built with Click.91+92+Check it:93+94+<div class="termy">95+96+```console97+$ python main.py98+99+// Notice we have both subcommands, top and hello100+Usage: main.py [OPTIONS] COMMAND [ARGS]...101+102+ Typer app, including Click subapp103+104+Options: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.107+108+ --help Show this message and exit.109+110+Commands:111+ hello Simple program that greets NAME for a total of COUNT times.112+ top Top level command, form Typer113+114+// Call the Typer part115+$ python main.py top116+117+The Typer app is at the top level118+119+// Call the Click part120+$ python main.py hello --name Camila121+122+Hello Camila!123+```124+125+</div>126+127+### Including a **Typer** app in a Click app128+129+The same way, you can do the contrary and include a **Typer** sub app in a bigger Click app:130+131+```Python hl_lines="31 33 36"132+{!./src/using_click/tutorial004.py!}133+```134+135+Notice 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.136+137+Then 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.138+139+In this case, the original Click app includes the **Typer** app.140+141+And then we call the *original Click* app, not the Typer app.142+143+Check it:144+145+<div class="termy">146+147+```console148+$ python main.py149+150+// We get our Typer app down there in the sub command151+Usage: main.py [OPTIONS] COMMAND [ARGS]...152+153+Options:154+ --help Show this message and exit.155+156+Commands:157+ dropdb158+ initdb159+ sub A single-command Typer sub app160+161+162+// Use the Click part163+$ python main.py initdb164+165+Initialized the database166+167+// And use the Typer part168+$ python main.py sub169+170+Typer is now below Click, the Click app is the top level171+```172+173+</div>174+175+## About Click decorators176+177+Typer apps don't work with Click decorators directly.178+179+This is because **Typer** doesn't modify functions to add metadata or to convert them to another object like Click does.180+181+So, things like `@click.pass_context` won't work.182+183+Most of the functionality provided by decorators in Click has an alternative way of doing it in **Typer**.184+185+For example, to access the context, you can just declare a function parameter of type `typer.Context`.186+187+!!! 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}189+190+But 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
1+import subprocess2+3+from click.testing import CliRunner4+5+from using_click import tutorial003 as mod6+7+runner = CliRunner()8+9+10+def 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.stdout15+16+17+def test_typer():18+ result = runner.invoke(mod.typer_click_object, ["top"])19+ assert "The Typer app is at the top level" in result.stdout20+21+22+def test_click():23+ result = runner.invoke(mod.typer_click_object, ["hello", "--name", "Camila"])24+ assert "Hello Camila!" in result.stdout25+26+27+def 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.stdoutadded:tests/test_tutorial/test_using_click/test_tutorial004.py+39 added
1+import subprocess2+3+from click.testing import CliRunner4+5+from using_click import tutorial004 as mod6+7+runner = CliRunner()8+9+10+def test_cli():11+ result = runner.invoke(mod.cli, [])12+ assert "Usage" in result.stdout13+ assert "dropdb" in result.stdout14+ assert "sub" in result.stdout15+16+17+def 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.stdout20+21+22+def test_click_initdb():23+ result = runner.invoke(mod.cli, ["initdb"])24+ assert "Initialized the database" in result.stdout25+26+27+def test_click_dropdb():28+ result = runner.invoke(mod.cli, ["dropdb"])29+ assert "Dropped the database" in result.stdout30+31+32+def 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.stdoutmodified:mkdocs.yml+1 added
69 unmodified lines70717273747576777841 unmodified lines69 unmodified lines - Progress Bar: 'tutorial/progressbar.md' - CLI Application Directory: 'tutorial/app-dir.md' - Launching Applications: 'tutorial/launch.md' - Testing: 'tutorial/testing.md' - Using Click: 'tutorial/using-click.md' - Typer CLI - completion for small scripts: 'typer-cli.md' - Alternatives, Inspiration and Comparisons: 'alternatives.md' - Help Typer - Get Help: 'help-typer.md' - Development - Contributing: 'contributing.md'41 unmodified lines