Skip to content
Myr

:sparkles: Add docs for testing, password, version, context. Extra tests, include callback and autocompletion PR (#68)

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

* :sparkles: Implement custom handling for callbacks with types * :sparkles: Implement type-based handling for completion functions * :sparkles: Add examples for custom completion * :memo: Add docs for custom autocompletion * :white_check_mark: Add tests for autocompletion * :sparkles: Document using the context * :white_check_mark: Add tests for using the context * :white_check_mark: Add tests init for context * :wrench: Update Mypy config * :white_check_mark: Add extra tests for completion * :pencil2: Fix format, typos, and minor texts * :sparkles: Update docs for printing, include stdout, stderr, and stdin * :pencil2: Add references to FastAPI, fix typos * :pencil2: Fix typo in Typer CLI * :memo: Update docs for version * :memo: Update docs for callbacks * :memo: Update references to stdout/stderr in autocompletion * :memo: Add docs for password in CLI option * :memo: Add docs and tests for Testing * :memo: Add new sections to docs * :art: Fix formatting

authored by Sebastián Ramírez · committed by GitHub · parent eec98ba · Browse files · 88 files+2760 added−83 removed
This commit

State

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

Diff stats

88 files+2760 added−83 removed

  • tests:+846 added−6 removed
  • other:+1914 added−77 removed

88 files+2760 added−83 removed

added:docs/src/commands/context/tutorial001.py+25 added
1import typer23app = typer.Typer()456@app.command()7def create(username: str):8 typer.echo(f"Creating user: {username}")91011@app.command()12def delete(username: str):13 typer.echo(f"Deleting user: {username}")141516@app.callback()17def main(ctx: typer.Context):18 """19 Manage users in the awesome CLI app.20 """21 typer.echo(f"About to execute command: {ctx.invoked_subcommand}")222324if __name__ == "__main__":25 app()
added:docs/src/commands/context/tutorial002.py+25 added
1import typer23app = typer.Typer()456@app.command()7def create(username: str):8 typer.echo(f"Creating user: {username}")91011@app.command()12def delete(username: str):13 typer.echo(f"Deleting user: {username}")141516@app.callback(invoke_without_command=True)17def main():18 """19 Manage users in the awesome CLI app.20 """21 typer.echo("Initializing database")222324if __name__ == "__main__":25 app()
added:docs/src/commands/context/tutorial003.py+26 added
1import typer23app = typer.Typer()456@app.command()7def create(username: str):8 typer.echo(f"Creating user: {username}")91011@app.command()12def delete(username: str):13 typer.echo(f"Deleting user: {username}")141516@app.callback(invoke_without_command=True)17def main(ctx: typer.Context):18 """19 Manage users in the awesome CLI app.20 """21 if ctx.invoked_subcommand is None:22 typer.echo("Initializing database")232425if __name__ == "__main__":26 app()
added:docs/src/commands/context/tutorial004.py+15 added
1import typer23app = typer.Typer()456@app.command(7 context_settings={"allow_extra_args": True, "ignore_unknown_options": True}8)9def main(ctx: typer.Context):10 for extra_arg in ctx.args:11 typer.echo(f"Got extra arg: {extra_arg}")121314if __name__ == "__main__":15 app()
added:docs/src/options/autocompletion/tutorial001.py+9 added
1import typer234def main(name: str = typer.Option("World", help="The name to say hi to.")):5 typer.echo(f"Hello {name}")678if __name__ == "__main__":9 typer.run(main)
added:docs/src/options/autocompletion/tutorial002.py+17 added
1import typer234def complete_name():5 return ["Camila", "Carlos", "Sebastian"]678def main(9 name: str = typer.Option(10 "World", help="The name to say hi to.", autocompletion=complete_name11 )12):13 typer.echo(f"Hello {name}")141516if __name__ == "__main__":17 typer.run(main)
added:docs/src/options/autocompletion/tutorial003.py+23 added
1import typer23valid_names = ["Camila", "Carlos", "Sebastian"]456def complete_name(incomplete: str):7 completion = []8 for name in valid_names:9 if name.startswith(incomplete):10 completion.append(name)11 return completion121314def main(15 name: str = typer.Option(16 "World", help="The name to say hi to.", autocompletion=complete_name17 )18):19 typer.echo(f"Hello {name}")202122if __name__ == "__main__":23 typer.run(main)
added:docs/src/options/autocompletion/tutorial004.py+28 added
1import typer23valid_completion_items = [4 ("Camila", "The reader of books."),5 ("Carlos", "The writer of scripts."),6 ("Sebastian", "The type hints guy."),7]8910def complete_name(incomplete: str):11 completion = []12 for name, help_text in valid_completion_items:13 if name.startswith(incomplete):14 completion_item = (name, help_text)15 completion.append(completion_item)16 return completion171819def main(20 name: str = typer.Option(21 "World", help="The name to say hi to.", autocompletion=complete_name22 )23):24 typer.echo(f"Hello {name}")252627if __name__ == "__main__":28 typer.run(main)
added:docs/src/options/autocompletion/tutorial005.py+25 added
1import typer23valid_completion_items = [4 ("Camila", "The reader of books."),5 ("Carlos", "The writer of scripts."),6 ("Sebastian", "The type hints guy."),7]8910def complete_name(incomplete: str):11 for name, help_text in valid_completion_items:12 if name.startswith(incomplete):13 yield (name, help_text)141516def main(17 name: str = typer.Option(18 "World", help="The name to say hi to.", autocompletion=complete_name19 )20):21 typer.echo(f"Hello {name}")222324if __name__ == "__main__":25 typer.run(main)
added:docs/src/options/autocompletion/tutorial006.py+12 added
1from typing import List23import typer456def main(name: List[str] = typer.Option(["World"], help="The name to say hi to.")):7 for each_name in name:8 typer.echo(f"Hello {each_name}")91011if __name__ == "__main__":12 typer.run(main)
added:docs/src/options/autocompletion/tutorial007.py+29 added
1from typing import List23import typer45valid_completion_items = [6 ("Camila", "The reader of books."),7 ("Carlos", "The writer of scripts."),8 ("Sebastian", "The type hints guy."),9]101112def complete_name(ctx: typer.Context, incomplete: str):13 names = ctx.params.get("name") or []14 for name, help_text in valid_completion_items:15 if name.startswith(incomplete) and name not in names:16 yield (name, help_text)171819def main(20 name: List[str] = typer.Option(21 ["World"], help="The name to say hi to.", autocompletion=complete_name22 )23):24 for n in name:25 typer.echo(f"Hello {n}")262728if __name__ == "__main__":29 typer.run(main)
added:docs/src/options/autocompletion/tutorial008.py+29 added
1from typing import List23import typer45valid_completion_items = [6 ("Camila", "The reader of books."),7 ("Carlos", "The writer of scripts."),8 ("Sebastian", "The type hints guy."),9]101112def complete_name(args: List[str], incomplete: str):13 typer.echo(f"{args}", err=True)14 for name, help_text in valid_completion_items:15 if name.startswith(incomplete):16 yield (name, help_text)171819def main(20 name: List[str] = typer.Option(21 ["World"], help="The name to say hi to.", autocompletion=complete_name22 )23):24 for n in name:25 typer.echo(f"Hello {n}")262728if __name__ == "__main__":29 typer.run(main)
added:docs/src/options/autocompletion/tutorial009.py+30 added
1from typing import List23import typer45valid_completion_items = [6 ("Camila", "The reader of books."),7 ("Carlos", "The writer of scripts."),8 ("Sebastian", "The type hints guy."),9]101112def complete_name(ctx: typer.Context, args: List[str], incomplete: str):13 typer.echo(f"{args}", err=True)14 names = ctx.params.get("name") or []15 for name, help_text in valid_completion_items:16 if name.startswith(incomplete) and name not in names:17 yield (name, help_text)181920def main(21 name: List[str] = typer.Option(22 ["World"], help="The name to say hi to.", autocompletion=complete_name23 )24):25 for n in name:26 typer.echo(f"Hello {n}")272829if __name__ == "__main__":30 typer.run(main)
added:docs/src/options/callback/tutorial001.py+15 added
1import typer234def name_callback(value: str):5 if value != "Camila":6 raise typer.BadParameter("Only Camila is allowed")7 return value8910def main(name: str = typer.Option(..., callback=name_callback)):11 typer.echo(f"Hello {name}")121314if __name__ == "__main__":15 typer.run(main)
added:docs/src/options/callback/tutorial002.py+16 added
1import typer234def name_callback(value: str):5 typer.echo("Validating name")6 if value != "Camila":7 raise typer.BadParameter("Only Camila is allowed")8 return value91011def main(name: str = typer.Option(..., callback=name_callback)):12 typer.echo(f"Hello {name}")131415if __name__ == "__main__":16 typer.run(main)
added:docs/src/options/callback/tutorial003.py+18 added
1import typer234def name_callback(ctx: typer.Context, value: str):5 if ctx.resilient_parsing:6 return7 typer.echo("Validating name")8 if value != "Camila":9 raise typer.BadParameter("Only Camila is allowed")10 return value111213def main(name: str = typer.Option(..., callback=name_callback)):14 typer.echo(f"Hello {name}")151617if __name__ == "__main__":18 typer.run(main)
added:docs/src/options/callback/tutorial004.py+18 added
1import typer234def name_callback(ctx: typer.Context, param: typer.CallbackParam, value: str):5 if ctx.resilient_parsing:6 return7 typer.echo(f"Validating param: {param.name}")8 if value != "Camila":9 raise typer.BadParameter("Only Camila is allowed")10 return value111213def main(name: str = typer.Option(..., callback=name_callback)):14 typer.echo(f"Hello {name}")151617if __name__ == "__main__":18 typer.run(main)
added:docs/src/options/password/tutorial001.py+11 added
1import typer234def main(5 name: str, email: str = typer.Option(..., prompt=True, confirmation_prompt=True)6):7 typer.echo(f"Hello {name}, your email is {email}")8910if __name__ == "__main__":11 typer.run(main)
added:docs/src/options/password/tutorial002.py+15 added
1import typer234def main(5 name: str,6 password: str = typer.Option(7 ..., prompt=True, confirmation_prompt=True, hide_input=True8 ),9):10 typer.echo(f"Hello {name}. Doing something very secure with password.")11 typer.echo(f"...just kidding, here it is, very insecure: {password}")121314if __name__ == "__main__":15 typer.run(main)
modified:docs/src/options/prompt/tutorial002.py+1 added-2 removed
1import typer234def main(5 name: str,6 lastname: str = typer.Option(..., prompt="Please tell me your last name"),5 name: str, lastname: str = typer.Option(..., prompt="Please tell me your last name")6):7 typer.echo(f"Hello {name} {lastname}")89
2 unmodified lines
added:docs/src/options/version/tutorial001.py+20 added
1import typer23__version__ = "0.1.0"456def version_callback(value: bool):7 if value:8 typer.echo(f"Awesome CLI Version: {__version__}")9 raise typer.Exit()101112def main(13 name: str = typer.Option("World"),14 version: bool = typer.Option(None, "--version", callback=version_callback),15):16 typer.echo(f"Hello {name}")171819if __name__ == "__main__":20 typer.run(main)
added:docs/src/options/version/tutorial002.py+25 added
1import typer23__version__ = "0.1.0"456def version_callback(value: bool):7 if value:8 typer.echo(f"Awesome CLI Version: {__version__}")9 raise typer.Exit()101112def name_callback(name: str):13 if name != "Camila":14 raise typer.BadParameter("Only Camila is allowed")151617def main(18 name: str = typer.Option(..., callback=name_callback),19 version: bool = typer.Option(None, "--version", callback=version_callback),20):21 typer.echo(f"Hello {name}")222324if __name__ == "__main__":25 typer.run(main)
added:docs/src/options/version/tutorial003.py+28 added
1import typer23__version__ = "0.1.0"456def version_callback(value: bool):7 if value:8 typer.echo(f"Awesome CLI Version: {__version__}")9 raise typer.Exit()101112def name_callback(name: str):13 if name != "Camila":14 raise typer.BadParameter("Only Camila is allowed")15 return name161718def main(19 name: str = typer.Option(..., callback=name_callback),20 version: bool = typer.Option(21 None, "--version", callback=version_callback, is_eager=True22 ),23):24 typer.echo(f"Hello {name}")252627if __name__ == "__main__":28 typer.run(main)
modified:docs/src/parameter_types/index/tutorial001.py+1 added-3 removed
1import typer234def main(5 name: str, age: int = 20, height_meters: float = 1.89, female: bool = True,6):4def main(name: str, age: int = 20, height_meters: float = 1.89, female: bool = True):5 typer.echo(f"NAME is {name}, of type: {type(name)}")6 typer.echo(f"--age is {age}, of type: {type(age)}")7 typer.echo(f"--height-meters is {height_meters}, of type: {type(height_meters)}")8 typer.echo(f"--female is {female}, of type: {type(female)}")
4 unmodified lines
added:docs/src/printing/tutorial003.py+9 added
1import typer234def main():5 typer.echo(f"Here is something written to standard error", err=True)678if __name__ == "__main__":9 typer.run(main)
added:docs/src/testing/app01/__init__.py
added:docs/src/testing/app01/main.py+14 added
1import typer23app = typer.Typer()456@app.command()7def main(name: str, city: str = None):8 typer.echo(f"Hello {name}")9 if city:10 typer.echo(f"Let's have a coffee in {city}")111213if __name__ == "__main__":14 app()
added:docs/src/testing/app01/test_main.py+12 added
1from typer.testing import CliRunner23from .main import app45runner = CliRunner()678def test_app():9 result = runner.invoke(app, ["Camila", "--city", "Berlin"])10 assert result.exit_code == 011 assert "Hello Camila" in result.stdout12 assert "Let's have a coffee in Berlin" in result.stdout
added:docs/src/testing/app02/__init__.py
added:docs/src/testing/app02/main.py+12 added
1import typer23app = typer.Typer()456@app.command()7def main(name: str, email: str = typer.Option(..., prompt=True)):8 typer.echo(f"Hello {name}, your email is: {email}")91011if __name__ == "__main__":12 app()
added:docs/src/testing/app02/test_main.py+11 added
1from typer.testing import CliRunner23from .main import app45runner = CliRunner()678def test_app():9 result = runner.invoke(app, ["Camila"], input="camila@example.com\n")10 assert result.exit_code == 011 assert "Hello Camila, your email is: camila@example.com" in result.stdout
added:docs/src/testing/app03/__init__.py
added:docs/src/testing/app03/main.py+9 added
1import typer234def main(name: str = "World"):5 typer.echo(f"Hello {name}")678if __name__ == "__main__":9 typer.run(main)
added:docs/src/testing/app03/test_main.py+15 added
1import typer2from typer.testing import CliRunner34from .main import main56app = typer.Typer()7app.command()(main)89runner = CliRunner()101112def test_app():13 result = runner.invoke(app, ["--name", "Camila"])14 assert result.exit_code == 015 assert "Hello Camila" in result.stdout
modified:docs/tutorial/commands/callback.md+21 added
160 unmodified lines
161Creating user: Camila162```163164</div>165166## Click Group167168If you come from Click, this **Typer** callback is the equivalent of the function in a <a href="https://click.palletsprojects.com/en/7.x/quickstart/#nesting-commands" class="external-link" target="_blank">Click Group</a>.169170For example:171172```Python173import click174175@click.group()176def cli():177 pass178```179180The original function `cli` would be the equivalent of a Typer callback.181182!!! note "Technical Details"183 When using Click, it converts that `cli` variable to a Click `Group` object. And then the original function no longer exists in that variable.184185 **Typer** doesn't do that, the callback function is not modified, only registered in the `typer.Typer` app. This is intentional, it's part of **Typer**'s design, to allow having editor auto completion and type checks.
added:docs/tutorial/commands/context.md+130 added
1When you create a **Typer** application it uses Click underneath. And every Click application has a special object called a <a href="https://click.palletsprojects.com/en/7.x/commands/#nested-handling-and-contexts" class="external-link" target="_blank">"Context"</a> that is normally hidden.23But you can access the context by declaring a function parameter of type `typer.Context`.45You might have read it in [CLI Option Callback and Context](../options/callback-and-context.md){.internal-link target=_blank}.67The same way, in commands or in the main `Typer` callback you can access the context by declaring a function parameter of type `typer.Context`.89## Getting the context1011For example, let's say that you want to execute some logic in a `Typer` callback depending on the subcommand that is being called.1213You can get the name of the subcommand from the context:1415```Python hl_lines="17 21"16{!./src/commands/context/tutorial001.py!}17```1819Check it:2021<div class="termy">2223```console24$ python main.py create Camila2526// We get the message from the callback27About to execute command: create28Creating user: Camila2930$ python main.py delete Camila3132// We get the message from the callback, this time with delete33About to execute command: delete34Deleting user: Camila35```3637</div>3839## Executable callback4041By default, the callback is only executed right before executing a command.4243And if no command is provided, the help message is shown.4445But we could make it run even without a subcommand with `invoke_without_command=True`:4647```Python hl_lines="16"48{!./src/commands/context/tutorial002.py!}49```5051Check it:5253<div class="termy">5455```console56$ python main.py5758// The callback is executed, we don't get the default help message59Initializing database6061// Try with a command62$ python main.py create Camila6364// The callback is still executed65Initializing database66Creating user: Camila67```6869</div>7071## Exclusive executable callback7273We might not want the callback to be executed if there's already other command that will be executed.7475For that, we can get the `typer.Context` and check if there's an invoked command in `ctx.invoked_subcommand`.7677If it's `None`, it means that we are not calling a subcommand but the main program (the callback) directly:7879```Python hl_lines="17 21"80{!./src/commands/context/tutorial003.py!}81```8283Check it:8485<div class="termy">8687```console88$ python main.py8990// The callback is executed91Initializing database9293// Check it with a subcommand94$ python main.py create Camila9596// This time the callback is not executed97Creating user: Camila98```99100</div>101102## Configuring the context103104You can pass configurations for the context when creating a command or callback.105106To read more about the available configurations check the docs for <a href="https://click.palletsprojects.com/en/7.x/api/#context" class="external-link" target="_blank">Click's `Context`</a>.107108For example, you could keep additional *CLI parameters* not declared in your CLI program with `ignore_unknown_options` and `allow_extra_args`.109110Then you can access those extra raw *CLI parameters* as a `list` of `str` in `ctx.args`:111112```Python hl_lines="7 9 10"113{!./src/commands/context/tutorial004.py!}114```115116<div class="termy">117118```console119$ python main.py --name Camila --city Berlin120121Got extra arg: --name122Got extra arg: Camila123Got extra arg: --city124Got extra arg: Berlin125```126127</div>128129!!! tip130 Notice that it saves all the extra *CLI parameters* as a raw `list` of `str`, including the *CLI option* names and values, everything together.
modified:docs/tutorial/commands/index.md+12 added-3 removed
1We have seen how to create a CLI program with possibly several *CLI Options* and *CLI Arguments*.1We have seen how to create a CLI program with possibly several *CLI options* and *CLI arguments*.23But **Typer** allows you to create CLI programs with several commands (also known as subcommands).45For example, the program `git` has several commands.
22 unmodified lines
2829It's like if the same big program `git` had several small programs inside.3031!!! tip32 A command looks the same as a *CLI argument*, it's just some name without a preceding `--`. But commands have predefined name, and are used to group different sets of functionalities into the same CLI application.32 A command looks the same as a *CLI argument*, it's just some name without a preceding `--`. But commands have a predefined name, and are used to group different sets of functionalities into the same CLI application.3334## Command or subcommand3536It's common to call a CLI program a "command".
7 unmodified lines
44## Explicit application4546Before creating CLI applications with multiple commands/subcommands we need to understand how to create an explicit `typer.Typer()` application.4748In the *CLI Options* and *CLI Argument* tutorials you have seen how to create a single function and then pass that function to `typer.run()`.48In the *CLI options* and *CLI argument* tutorials you have seen how to create a single function and then pass that function to `typer.run()`.4950For example:5152```Python hl_lines="9"
114 unmodified lines
167168!!! tip169 By default, the names of the commands are generated from the function name.170171## Click Group172173If you come from Click, a `typer.Typer` app with subcommands is more or less the equivalent of a <a href="https://click.palletsprojects.com/en/7.x/quickstart/#nesting-commands" class="external-link" target="_blank">Click Group</a>.174175!!! note "Technical Details"176 A `typer.Typer` app is *not* a Click Group, but it provides the equivalent functionality. And it creates a Click Group when calling it.177178 It is not directly a Group because **Typer** doesn't modify the functions in your code to convert them to another type of object, it only registers them.179180## Decorator Technical Details181182When you use `@app.command()` the function under the decorator is registered in the **Typer** application and is then used later by the application.183
8 unmodified lines
added:docs/tutorial/options/autocompletion.md+363 added
1As you have seen, apps built with **Typer** have completion in your shell that works when you create a Python package or using **Typer CLI**.23It normally completes *CLI options*, *CLI arguments*, and subcommands (that you will learn about later).45But you can also provide auto completion for the **values** of *CLI options* and *CLI arguments*. We will learn about that here.67## Review completion89Before checking how to provide custom completions, let's check again how it works.1011After installing completion (for your own Python package or for **Typer CLI**), when you use your CLI program and start adding a *CLI option* with `--` an then hit <kbd>TAB</kbd>, your shell will show you the available *CLI options* (the same for *CLI arguments*, etc).1213To check it quickly without creating a new Python package, install [Typer CLI](../../typer-cli.md){.internal-link target=_blank}.1415Then let's create small example script:1617```Python18{!./src/options/autocompletion/tutorial001.py!}19```2021And let's try it with **Typer CLI** to get completion:2223<div class="termy">2425```console26// Hit the TAB key in your keyboard below where you see the: [TAB]27$ typer ./main.py [TAB][TAB]2829// Depending on your terminal/shell you will get some completion like this ✨30run -- Run the provided Typer app.31utils -- Extra utility commands for Typer apps.3233// Then try with "run" and --34$ typer ./main.py run --[TAB][TAB]3536// You will get completion for --name, depending on your terminal it will look something like this37--name -- The name to say hi to.3839// And you can run it as if it was with Python directly40$ typer ./main.py run --name Camila4142Hello Camila43```4445</div>4647## Custom completion for values4849Right now we get completion for the *CLI option* names, but not for the values.5051We can provide completion for the values creating an `autocompletion` function, similar to the `callback` functions from [CLI Option Callback and Context](./callback-and-context.md){.internal-link target=_blank}:5253```Python hl_lines="4 5 10"54{!./src/options/autocompletion/tutorial002.py!}55```5657We return a `list` of strings from the `complete_name()` function.5859And then we get those values when using completion:6061<div class="termy">6263```console64$ typer ./main.py run --name [TAB][TAB]6566// We get the values returned from the function 🎉67Camila Carlos Sebastian68```6970</div>7172We got the basics working. Now let's improve it.7374## Check the incomplete value7576Right now, we always return those values, even if users start typing `Sebast` and then hit <kbd>TAB</kbd>, they will also get the completion for `Camila` and `Carlos` (depending on the shell), while we should only get completion for `Sebastian`.7778But we can fix that so that it always works correctly.7980Modify the `complete_name()` function to receive a parameter of type `str`, it will contain the incomplete value.8182Then we can check and return only the values that start with the incomplete value from the command line:8384```Python hl_lines="6 7 8 9 10 11"85{!./src/options/autocompletion/tutorial003.py!}86```8788Now let's try it:8990<div class="termy">9192```console93$ typer ./main.py run --name Ca[TAB][TAB]9495// We get the values returned from the function that start with Ca 🎉96Camila Carlos97```9899</div>100101Now we are only returning the valid values, that start with `Ca`, we are no longer returning `Sebastian` as a completion option.102103!!! tip104 You have to declare the incomplete value of type `str` and that's what you will receive in the function.105106 No matter if the actual value will be an `int`, or something else, when doing completion, you will only get a `str` as the incomplete value.107108 And the same way, you can only return `str`, not `int`, etc.109110## Add help to completions111112Right now we are returning a `list` of `str`.113114But some shells (Zsh, Fish, PowerShell) are capable of showing extra help text for completion.115116We can provide that extra help text so that those shells can show it.117118In the `complete_name()` function, instead of providing one `str` per completion element, we provide a `tuple` with 2 items. The first item is the actual completion string, and the second item is the help text.119120So, in the end, we return a `list` of `tuples` of `str`:121122```Python hl_lines="3 4 5 6 7 10 11 12 13 14 15 16"123{!./src/options/autocompletion/tutorial004.py!}124```125126!!! tip127 If you want to have help text for each item, make sure each item in the list is a `tuple`. Not a `list`.128129 Click checks specifically for a `tuple` when extracting the help text.130131 So in the end, the return will be a `list` (or other iterable) of `tuples` of 2 `str`.132133!!! info134 The help text will be visible in Zsh, Fish, and PowerShell.135136 Bash doesn't support showing the help text, but completion will still work the same.137138If you have a shell like Zsh, it would look like:139140<div class="termy">141142```console143$ typer ./main.py run --name [TAB][TAB]144145// We get the completion items with their help text 🎉146Camila -- The reader of books.147Carlos -- The writer of scripts.148Sebastian -- The type hints guy.149```150151</div>152153## Simplify with `yield`154155Instead of creating and returning a list with values (`str` or `tuple`), we can use `yield` with each value that we want in the completion.156157That way our function will be a <a href="https://docs.python.org/3.8/glossary.html#index-19" class="external-link" target="_blank">generator</a> that **Typer** (actually Click) can iterate:158159```Python hl_lines="10 11 12 13"160{!./src/options/autocompletion/tutorial005.py!}161```162163That simplifies our code a bit and works the same.164165!!! tip166 If all the `yield` part seems complex for you, don't worry, you can just use the version with the `list` above.167168 In the end, that's just to save us a couple of lines of code.169170!!! info171 The function can use `yield`, so it doesn't have to return strictly a `list`, it just has to be <a href="https://docs.python.org/3.8/glossary.html#term-iterable" class="external-link" target="_blank">iterable</a>.172173 But each of the elements for completion has to be a `str` or a `tuple` (when containing a help text).174175## Access other *CLI parameters* with the Context176177Let's say that now we want to modify the program to be able to "say hi" to multiple people at the same time.178179So, we will allow multiple `--name` *CLI options*.180181!!! tip182 You will learn more about *CLI parameters* with multiple values later in the tutorial.183184 So, for now, take this as a sneak peek 😉.185186For this we use a `List` of `str`:187188```Python hl_lines="6 7 8"189{!./src/options/autocompletion/tutorial006.py!}190```191192And then we can use it like:193194<div class="termy">195196```console197$ typer ./main.py run --name Camila --name Sebastian198199Hello Camila200Hello Sebastian201```202203</div>204205### Getting completion for multiple values206207And the same way as before, we want to provide **completion** for those names. But we don't want to provide the **same names** for completion if they were already given in previous parameters.208209For that, we will access and use the "Context". When you create a **Typer** application it uses Click underneath. And every Click application has a special object called a <a href="https://click.palletsprojects.com/en/7.x/commands/#nested-handling-and-contexts" class="external-link" target="_blank">"Context"</a> that is normally hidden.210211But you can access the context by declaring a function parameter of type `typer.Context`.212213And from that context you can get the current values for each parameter.214215```Python hl_lines="12 13 15"216{!./src/options/autocompletion/tutorial007.py!}217```218219We are getting the `names` already provided with `--name` in the command line before this completion was triggered.220221If there's no `--name` in the command line, it will be `None`, so we use `or []` to make sure we have a `list` (even if empty) to check its contents later.222223Then, when we have a completion candidate, we check if each `name` was already provided with `--name` by checking if it's in that list of `names` with `name not in names`.224225And then we `yield` each item that has not being used yet.226227Check it:228229<div class="termy">230231```console232$ typer ./main.py run --name [TAB][TAB]233234// The first time we trigger completion, we get all the names235Camila -- The reader of books.236Carlos -- The writer of scripts.237Sebastian -- The type hints guy.238239// Add a name and trigger completion again240$ typer ./main.py run --name Sebastian --name Ca[TAB][TAB]241242// Now we get completion only for the names we haven't used 🎉243Camila -- The reader of books.244Carlos -- The writer of scripts.245246// And if we add another of the available names:247$ typer ./main.py run --name Sebastian --name Camila --name [TAB][TAB]248249// We get completion for the only available one250Carlos -- The writer of scripts.251```252253</div>254255!!! tip256 It's quite possible that if there's only one option left, your shell will complete it right away instead of showing the option with the help text, to save you more typing.257258## Getting the raw *CLI parameters*259260You can also get the raw *CLI parameters*, just a `list` of `str` with everything passed in the command line before the incomplete value.261262For example, something like `["typer", "main.py", "run", "--name"]`.263264!!! tip265 This would be for advanced scenarios, in most use cases you would be better of using the context.266267 But it's still possible if you need it.268269As a simple example, let's show it on the screen before completion.270271Because completion is based on the output printed by your program (handled internally by **Typer**), during completion we can't just print something else as we normally do.272273### Printing to "standard error"274275!!! tip276 If you need a refresher about what is "standard output" and "standard error" check the section in [Printing and Colors: "Standard Output" and "Standard Error"](../printing.md#standard-output-and-standard-error){.internal-link target=_blank}.277278The completion system only reads from "standard output", so, printing to "standard error" won't break completion. 🚀279280You can print to "standard error" with `typer.echo("some text", err=True)`.281282Using `err=True` tells **Typer** (actually Click) that the output should be shown in "standard error".283284```Python hl_lines="12 13"285{!./src/options/autocompletion/tutorial008.py!}286```287288We get all the *CLI parameters* as a raw `list` of `str` by declaring a parameter with type `List[str]`, here it's named `args`.289290!!! tip291 Here we name the list of all the raw *CLI parameters* `args` because that's the convention with Click.292293 But it doesn't contain only *CLI arguments*, it has everything, including *CLI options* and values, as a raw `list` of `str`.294295And then we just print it to "standard error".296297<div class="termy">298299```console300$ typer ./main.py run --name [TAB][TAB]301302// First we see the raw CLI parameters303['./main.py', 'run', '--name']304305// And then we see the actual completion306Camila -- The reader of books.307Carlos -- The writer of scripts.308Sebastian -- The type hints guy.309```310311</div>312313!!! tip314 This is a very simple (and quite useless) example, just so you know how it works and that you can use it.315316 But it's probably useful only in very advanced use cases.317318## Getting the Context and the raw *CLI parameters*319320Of course, you can declare everything if you need it, the context, the raw *CLI parameters*, and the incomplete `str`:321322```Python hl_lines="12"323{!./src/options/autocompletion/tutorial009.py!}324```325326Check it:327328<div class="termy">329330```console331$ typer ./main.py run --name [TAB][TAB]332333// First we see the raw CLI parameters334['./main.py', 'run', '--name']335336// And then we see the actual completion337Camila -- The reader of books.338Carlos -- The writer of scripts.339Sebastian -- The type hints guy.340341$ typer ./main.py run --name Sebastian --name Ca[TAB][TAB]342343// Again, we see the raw CLI parameters344['./main.py', 'run', '--name', 'Sebastian', '--name']345346// And then we see the rest of the valid completion items347Camila -- The reader of books.348Carlos -- The writer of scripts.349```350351</div>352353## Types, types everywhere354355**Typer** uses the type declarations to detect what it has to provide to your `autocompletion` function.356357You can declare function parameters of these types:358359* `str`: for the incomplete value.360* `typer.Context`: for the current context.361* `List[str]`: for the raw *CLI parameters*.362363It doesn't matter how you name them, in which order, or which ones of the 3 options you declare. It will all "**just work**" ✨
added:docs/tutorial/options/callback-and-context.md+217 added
1In some occasions you might want to have some custom logic for a specific *CLI parameter* (for a *CLI option* or *CLI argument*) that is executed with the value received from the terminal.23In those cases you can use a *CLI parameter* callback function.45## Validate *CLI parameters*67For example, you could do some validation before the rest of the code is executed.89```Python hl_lines="4 5 6 7 10"10{!./src/options/callback/tutorial001.py!}11```1213Here you pass a function to `typer.Option()` or `typer.Argument()` with the keyword argument `callback`.1415The function receives the value from the command line. It can do anything with it, and then return the value.1617In this case, if the `--name` is not `Camila` we raise a `typer.BadParameter()` exception.1819The `BadParameter` exception is special, it shows the error with the parameter that generated it.2021Check it:2223<div class="termy">2425```console26$ python main.py --name Camila2728Hello Camila2930$ python main.py --name Rick3132Usage: main.py [OPTIONS]3334// We get the error from the callback35Error: Invalid value for '--name': Only Camila is allowed36```3738</div>3940## Handling completion4142There's something to be aware of with callbacks and completion that requires some small special handling.4344But first let's just use completion in your shell (Bash, Zsh, Fish, or PowerShell).4546After installing completion (for your own Python package or for **Typer CLI**), when you use your CLI program and start adding a *CLI option* with `--` an then hit <kbd>TAB</kbd>, your shell will show you the available *CLI options* (the same for *CLI arguments*, etc).4748To check it quickly without creating a new Python package, install [Typer CLI](../../typer-cli.md){.internal-link target=_blank} and use it with the previous script:4950<div class="termy">5152```console53// Hit the TAB key in your keyboard below where you see the: [TAB]54$ typer ./main.py [TAB][TAB]5556// Depending on your terminal/shell you will get some completion like this ✨57run -- Run the provided Typer app.58utils -- Extra utility commands for Typer apps.5960// Then try with "run" and --help61$ typer ./main.py run --help6263// You get a help text with your CLI options as you normally would64Usage: typer run [OPTIONS]6566 Run the provided Typer app.6768Options:69 --name TEXT [required]70 --help Show this message and exit.7172// Then try completion with your program73$ typer ./main.py run --[TAB][TAB]7475// You get completion for CLI options76--help -- Show this message and exit.77--name7879// And you can run it as if it was with Python directly80$ typer ./main.py run --name Camila8182Hello Camila83```8485</div>8687### How shell completion works8889The way it works internally is that the shell/terminal will call your CLI program with some special environment variables (that hold the current *CLI parameters*, etc) and your CLI program will print some special values that the shell will use to present completion. All this is handled for you by **Typer** behind the scenes.9091But the main **important point** is that it is all based on values printed by your program that the shell reads.9293### Breaking completion in a callback9495Let's say that when the callback is running, we want to show a message saying that it's validating the name:9697```Python hl_lines="5"98{!./src/options/callback/tutorial002.py!}99```100101And because the callback will be called when the shell calls your program asking for completion, that message `"Validating name"` will be printed and it will break completion.102103It will look something like:104105<div class="termy">106107```console108// Run it normally109$ typer ./main.py run --name Camila110111// See the extra message "Validating name"112Validating name113Hello Camila114115$ typer ./main.py run --[TAB][TAB]116117// Some weird broken error message ⛔️118(eval):1: command not found: Validating119rutyper ./main.pyed Typer app.120```121122</div>123124### Fix completion - using the `Context`125126When you create a **Typer** application it uses Click underneath.127128And every Click application has a special object called a <a href="https://click.palletsprojects.com/en/7.x/commands/#nested-handling-and-contexts" class="external-link" target="_blank">"Context"</a> that is normally hidden.129130But you can access the context by declaring a function parameter of type `typer.Context`.131132The "context" has some additional data about the current execution of your program:133134```Python hl_lines="4 5 6"135{!./src/options/callback/tutorial003.py!}136```137138The `ctx.resilient_parsing` will be `True` when handling completion, so you can just return without printing anything else.139140But it will be `False` when calling the program normally. So you can continue the execution of your previous code.141142That's all is needed to fix completion 🚀143144Check it:145146<div class="termy">147148```console149$ typer ./main.py run --[TAB][TAB]150151// Now it works correctly 🎉152--help -- Show this message and exit.153--name154155// And you can call it normally156$ typer ./main.py run --name Camila157158Validating name159Hello Camila160```161162</div>163164## Using the `CallbackParam` object165166The same way you can access the `typer.Context` by declaring a function parameter with its value, you can declare another function parameter with type `typer.CallbackParam` to get the specific Click `Parameter` object.167168```Python hl_lines="4 7"169{!./src/options/callback/tutorial004.py!}170```171172It's probably not very common, but you could do it if you need it.173174For example if you had a callback that could be used by several *CLI parameters*, that way the callback could know which parameter is each time.175176Check it:177178<div class="termy">179180```console181$ python main.py --name Camila182183Validating param: name184Hello Camila185```186187</div>188189## Technical Details190191Because you get the relevant data in the callback function based on standard Python type annotations, you get type checks and autocompletion in your editor for free.192193And **Typer** will make sure you get the function parameters you want.194195You don't have to worry about their names, their order, etc.196197As it's based on standard Python types, it "**just works**". ✨198199### Click's `Parameter`200201The `typer.CallbackParam` is actually just a sub-class of Click's <a href="https://click.palletsprojects.com/en/7.x/api/#click.Parameter" class="external-link" target="_blank">`Parameter`</a>, so you get all the right completion in your editor.202203### Callback with type annotations204205You can get the `typer.Context` and the `typer.CallbackParam` simply by declaring a function parameter of each type.206207The order doesn't matter, the name of the function parameters doesn't matter.208209You could also get only the `typer.CallbackParam` and not the `typer.Context`, or vice versa, it will still work.210211### `value` function parameter212213The `value` function parameter in the callback can also have any name (e.g. `lastname`) and any type, but it should have the same type annotation as in the main function, because that's what it will receive.214215It's also possible to not declare its type. It will still work.216217And it's possible to not declare the `value` parameter at all, and, for example, only get the `typer.Context`. That will also work.
added:docs/tutorial/options/password.md+53 added
1Apart from having a prompt, you can make a *CLI option* have a `confirmation_prompt=True`:23```Python hl_lines="5"4{!./src/options/password/tutorial001.py!}5```67And the CLI program will ask for confirmation:89<div class="termy">1011```console12$ python main.py Camila1314// It prompts for the email15# Email: $ camila@example.com16# Repeat for confirmation: $ camila@example.com1718Hello Camila, your email is camila@example.com19```2021</div>2223## A Password prompt2425When receiving a password, it is very common (in most shells) to not show anything on the screen while typing the password.2627The program will still receive the password, but nothing will be shown on screen, not even `****`.2829You can achieve the same using `hide_input=True`.3031And if you combine it with `confirmation_prompt=True` you can easily receive a password with double confirmation:3233```Python hl_lines="6 7 8"34{!./src/options/password/tutorial002.py!}35```3637Check it:3839<div class="termy">4041```console42$ python main.py Camila4344// It prompts for the password, but doesn't show anything when you type45# Password: $ 46# Repeat for confirmation: $ 4748// Let's imagine the password typed was "typerrocks"49Hello Camila. Doing something very secure with password.50...just kidding, here it is, very insecure: typerrocks51```5253</div>
modified:docs/tutorial/options/prompt.md+1 added-1 removed
22 unmodified lines
23## Customize the prompt2425You can also set a custom prompt, passing the string that you want to use instead of just `True`:2627```Python hl_lines="6"27```Python hl_lines="5"28{!./src/options/prompt/tutorial002.py!}29```3031And then your program will ask for it using with your custom prompt:
57 unmodified lines
added:docs/tutorial/options/version.md+107 added
1You could use a callback to implement a `--version` *CLI option*.23It would show the version of your CLI program and then it would terminate it. Even before any other *CLI parameter* is processed.45## First version of `--version`67Let's see a first version of how it could look like:89```Python hl_lines="6 7 8 9 14"10{!./src/options/version/tutorial001.py!}11```1213!!! tip14 Notice that we don't have to get the `typer.Context` and check for `ctx.resilient_parsing` for completion to work, because we only print and modify the program when `--version` is passed, otherwise, nothing is printed or changed from the callback.1516If the `--version` *CLI option* is passed, we get a value `True` in the callback.1718Then we can print the version and raise `typer.Exit()` to make sure the program is terminated before anything else is executed.1920We also declare the explicit *CLI option* name `--version`, because we don't want an automatic `--no-version`, it would look awkward.2122Check it:2324<div class="termy">2526```console27$ python main.py --help2829// We get a --version, and don't get an awkward --no-version 🎉30Usage: main.py [OPTIONS]3132Options:33 --version34 --name TEXT35 --install-completion Install completion for the current shell.36 --show-completion Show completion for the current shell, to copy it or customize the installation.3738 --help Show this message and exit.394041// We can call it normally42$ python main.py --name Camila4344Hello Camila4546// And we can get the version47$ python main.py --version4849Awesome CLI Version: 0.1.05051// Because we exit in the callback, we don't get a "Hello World" message after the version 🚀52```5354</div>5556## Previous parameters and `is_eager`5758But now let's say that the `--name` *CLI option* that we declared before `--version` is required, and it has a callback that could exit the program:5960```Python hl_lines="12 13 14 18"61{!./src/options/version/tutorial002.py!}62```6364Then our CLI program could not work as expected in some cases as it is *right now*, because if we use `--version` after `--name` then the callback for `--name` will be processed before and we can get its error:6566<div class="termy">6768```console69$ python main.py --name Rick --version7071Only Camila is allowed72Aborted!73```7475</div>7677!!! tip78 We don't have to check for `ctx.resilient_parsing` in the `name_callback()` for completion to work, because we are not using `typer.echo()`, instead we are raising a `typer.BadParameter`.7980!!! note "Technical Details"81 `typer.BadParameter` prints the error to "standard error", not to "standard output", and because the completion system only reads from "standard output", it won't break completion.8283!!! info84 If you need a refresher about what is "standard output" and "standard error" check the section in [Printing and Colors: "Standard Output" and "Standard Error"](../printing.md#standard-output-and-standard-error){.internal-link target=_blank}.8586### Fix with `is_eager`8788For those cases, we can mark a *CLI parameter* (a *CLI option* or *CLI argument*) with `is_eager=True`.8990That will tell **Typer** (actually Click) that it should process this *CLI parameter* before the others:9192```Python hl_lines="21"93{!./src/options/version/tutorial003.py!}94```9596Check it:9798<div class="termy">99100```console101$ python main.py --name Rick --version102103// Now we only get the version, and the name is not used104Awesome CLI Version: 0.1.0105```106107</div>
modified:docs/tutorial/parameter-types/index.md+1 added-1 removed
4 unmodified lines
5When you declare a *CLI parameter* with some type **Typer** will convert the data received in the command line to that data type.67For example:89```Python hl_lines="5"9```Python hl_lines="4"10{!./src/parameter_types/index/tutorial001.py!}11```1213In this example, the value received for the *CLI argument* `NAME` will be treated as `str`.
52 unmodified lines
modified:docs/tutorial/arguments.md+1 added-1 removed
45 unmodified lines
46```Python hl_lines="4"47{!./src/arguments/tutorial001.py!}48```4950Before you had this function parameter:50Before, you had this function parameter:5152```Python53name: str54```
154 unmodified lines
modified:docs/tutorial/first-steps.md+5 added-5 removed
1## The simplest example23The simplest Typer file could look like this:3The simplest **Typer** file could look like this:45```Python6{!./src/first_steps/tutorial001.py!}7```
164 unmodified lines
172The program knows it has to show the size because it sees `--size`, not because of the order.173174A *CLI option* like `--size` doesn't depend on the order like a *CLI argument*.175176So, if you put the `--size` *before* the *CLI argument*, it still works:176So, if you put the `--size` *before* the *CLI argument*, it still works (in fact, that's the most common way of doing it):177178<div class="termy">179180```console
237 unmodified lines
418And a parameter like `name`, that doesn't have a default value, is considered *required*.419420### In CLIs421422When talking about command line interfaces/applications, the words **"argument"** and **"parameter"** are commonly used to refer to that data passed to a CLI app, those parameters.422When talking about command line interface applications, the words **"argument"** and **"parameter"** are commonly used to refer to that data passed to a CLI app, those parameters.423424But those words **don't imply** anything about the data being required, needing to be passed in a certain order, nor having a flag like `--lastname`.425426The parameters that come with a name like `--lastname` (and optionally a value) are commonly optional, not required. So, when talking about CLIs it's common to call them **optional arguments** or **optional parameters**. Sometimes these *optional parameters* that start with `--` are also called a **flag** or a **switch**.
3 unmodified lines
430### In **Typer**431432To try and make it a bit easier, we'll normally use the words "parameter" or "argument" to refer to Python functions.433434We'll use ***CLI argument*** to refer to those *CLI parameters* that depend on an order. That are **required** by default.434We'll use ***CLI argument*** to refer to those *CLI parameters* that depend on the specific order. That are **required** by default.435436And we'll use ***CLI option*** to refer to those *CLI parameters* that depend on a name that starts with `--` (like `--lastname`). That are **optional** by default.437438We will use ***CLI parameter*** to refer to both, *CLI arguments* and *CLI options*.
29 unmodified lines
468</div>469470...and it will give you auto completion in your terminal when you hit <kbd>TAB</kbd> for all your code.471472So you can use it to have auto completion as you continue with the tutorial.472So you can use it to have auto completion for your own scripts as you continue with the tutorial.473474!!! tip475 Your CLI application built with **Typer** won't need [Typer CLI](../typer-cli.md){.internal-link target=_blank} to have auto completion once you create a Python package.476
1 unmodified line
modified:docs/tutorial/index.md+5 added-5 removed
9 unmodified lines
10def type_example(name: str, formal: bool = False, intro: str = None):11 pass12```1314And your editor (and Typer) will know that:14And your editor (and **Typer**) will know that:1516* `name` is of type `str` and is a required parameter.17* `formal` is a `bool` and is by default `False`.18* `intro` is a `str`, and by default is `None`, so it's optional.1920These type hints are what give you autocomplete in your editor and several other features.2122Typer is based on these type hints.22**Typer** is based on these type hints.2324## Intro2526This tutorial shows you how to use **Typer** with all its features, step by step.
21 unmodified lines
48</div>4950It is **HIGHLY encouraged** that you write or copy the code, edit it and run it locally.5152Using it in your editor is what really shows you the benefits of Typer, seeing how little code you have to write, all the type checks, autocompletion, etc.52Using it in your editor is what really shows you the benefits of **Typer**, seeing how little code you have to write, all the type checks, autocompletion, etc.5354And running the examples is what will really help you understand what is going on.5556You can learn a lot more by running some examples and playing around with them than by reading all the docs here.
10 unmodified lines
6768```console69$ pip install typer[all]70---> 100%71Successfully installed typer click colorama click-completion71Successfully installed typer click colorama shellingham72```7374</div>7576...that also includes `colorama` and `click-completion`.76...that also includes `colorama` and `shellingham`.
modified:docs/tutorial/printing.md+58 added-1 removed
38 unmodified lines
39{!./src/printing/tutorial001.py!}40```4142!!! tip43 The parameters `fg` and `bg` receive strings with the color names. You could simply pass `fg="green"` and `bg="red"`.43 The parameters `fg` and `bg` receive strings with the color names for the "**f**ore**g**round" and "**b**ack**g**round" colors. You could simply pass `fg="green"` and `bg="red"`.4445 But **Typer** provides them all as variables like `typer.colors.GREEN` just so you can use autocompletion while selecting them.4647Check it:
32 unmodified lines
80<div class="use-termynal" data-termynal>81<span data-ty="input">python main.py Camila</span>82<span style="color: magenta;" data-ty>Welcome here Camila</span>83</div>8485## "Standard Output" and "Standard Error"8687The way printing works underneath is that the **operating system** (Linux, Windows, macOS) treats what we print as if our CLI program was **writing text** to a "**virtual file**" called "**standard output**".8889When our code "prints" things it is actually "writing" to this "virtual file" of "standard output".9091This might seem strange, but that's how the CLI program and the operating system interact with each other.9293And then the operating system **shows on the screen** whatever our CLI program "**wrote**" to that "**virtual file**" called "**standard output**".9495### Standard Error9697And there's another "**virtual file**" called "**standard error**" that is normally only used for errors.9899But we can also "print" to "standard error". And both are shown on the terminal to the users.100101!!! info102 If you use PowerShell it's quite possible that what you print to "standard error" won't be shown in the terminal.103104 In PowerShell, to see "standard error" you would have to check the variable `$Error`.105106 But it will work normally in Bash, Zsh, and Fish.107108### Printing to "standard error"109110You can print to "standard error" with `typer.echo("some text", err=True)`.111112Using `err=True` tells **Typer** (actually Click) that the output should be shown in "standard error".113114```Python hl_lines="5"115{!./src/printing/tutorial003.py!}116```117118When you try it in the terminal, it will probably just look the same:119120<div class="termy">121122```console123$ python main.py124125Here is something written to standard error126```127128</div>129130### "Standard Input"131132As a final detail, when you type text in your keyboard to your terminal, the operating system also considers it another "**virtual file**" that you are writing text to.133134This virtual file is called "**standard input**".135136### What is this for137138Right now this probably seems quite useless 🤷‍♂.139140But understanding that will come handy in the future, for example for autocompletion and testing.
modified:docs/tutorial/terminating.md+1 added-1 removed
85 unmodified lines
8687</div>8889!!! tip90 The error code might be used by other programs (for example a Bash script) that execute with your CLI program.90 The error code might be used by other programs (for example a Bash script) that execute your CLI program.9192## Abort9394There's a special exception that you can use to "abort" a program.
24 unmodified lines
added:docs/tutorial/testing.md+213 added
1Testing **Typer** applications is very easy with <a href="https://docs.pytest.org/en/latest/" class="external-link" target="_blank">pytest</a>.23Let's say you have an application `app/main.py` with:45```Python6{!./src/testing/app01/main.py!}7```89So, you would use it like:1011<div class="termy">1213```console14$ python main.py Camila --city Berlin1516Hello Camila17Let's have a coffee in Berlin18```1920</div>2122And the directory also has an empty `app/__init__.py` file.2324So, the `app` is a "Python package".2526## Test the app2728### Import and create a `CliRunner`2930Create another file/module `app/test_main.py`.3132Import `CliRunner` and create a `runner` object.3334This runner is what will "invoke" or "call" your command line application.3536```Python hl_lines="1 5"37{!./src/testing/app01/test_main.py!}38```3940!!! tip41 It's important that the name of the file starts with `test_`, that way pytest will be able to detect it and use it automatically.4243### Call the app4445Then create a function `test_app()`.4647And inside of the function, use the `runner` to `invoke` the application.4849The first parameter to `runner.invoke()` is a `Typer` app.5051The second parameter is a `list` of `str`, with all the text you would pass in the command line, right as you would pass it:5253```Python hl_lines="8 9"54{!./src/testing/app01/test_main.py!}55```5657!!! tip58 The name of the function has to start with `test_`, that way pytest can detect it and use it automatically.5960### Check the result6162Then, inside of the test function, add `assert` statements to ensure that everything in the result of the call is as it should be.6364```Python hl_lines="10 11 12"65{!./src/testing/app01/test_main.py!}66```6768Here we are checking that the exit code is 0, as it is for programs that exit without errors.6970Then we check that the text printed to "standard output" contains the text that our CLI program prints.7172!!! tip73 You could also check `result.stderr` for "standard error".7475!!! info76 If you need a refresher about what is "standard output" and "standard error" check the section in [Printing and Colors: "Standard Output" and "Standard Error"](printing.md#standard-output-and-standard-error){.internal-link target=_blank}.7778### Call `pytest`7980Then you can call `pytest` in your directory and it will run your tests:8182<div class="termy">8384```console85$ pytest8687================ test session starts ================88platform linux -- Python 3.6.9, pytest-5.3.5, py-1.8.1, pluggy-0.13.189rootdir: /home/user/code/superawesome-cli/app90plugins: forked-1.1.3, xdist-1.31.0, cov-2.8.191collected 1 item9293---> 100%9495test_main.py <span style="color: green;">. [100%]</span>9697<span style="color: green;">================= 1 passed in 0.03s =================</span>98```99100</div>101102## Testing input103104If you have a CLI with prompts, like:105106```Python hl_lines="7"107{!./src/testing/app02/main.py!}108```109110That you would use like:111112<div class="termy">113114```console115$ python main.py Camila116117# Email: $ camila@example.com118119Hello Camila, your email is: camila@example.com120```121122</div>123124You can test the input typed in the terminal using `input="camila@example.com\n"`.125126This is because what you type in the terminal goes to "**standard input**" and is handled by the operating system as if it was a "virtual file".127128!!! info129 If you need a refresher about what is "standard output", "standard error", and "standard input" check the section in [Printing and Colors: "Standard Output" and "Standard Error"](printing.md#standard-output-and-standard-error){.internal-link target=_blank}.130131When you hit the <kbd>ENTER</kbd> key after typing the email, that is just a "new line character". And in Python that is represented with `"\n"`.132133So, if you use `input="camila@example.com\n"` it means: "type `camila@example.com` in the terminal, then hit the <kbd>ENTER</kbd> key":134135```Python hl_lines="9"136{!./src/testing/app02/test_main.py!}137```138139## Test a function140141If you have a script and you never created an explicit `typer.Typer` app, like:142143```Python hl_lines="9"144{!./src/testing/app03/main.py!}145```146147...you can still test it, by creating an app during testing:148149```Python hl_lines="6 7 13"150{!./src/testing/app03/test_main.py!}151```152153Of course, if you are testing that script, it's probably easier/cleaner to just create the explicit `typer.Typer` app in `main.py` instead of creating it just during the test.154155But if you want to keep it that way, e.g. because it's a simple example in documentation, then you can use that trick.156157### About the `app.command` decorator158159Notice the `app.command()(main)`.160161If it's not obvious what it's doing, continue reading...162163You would normally write something like:164165```Python166@app.command()167def main(name: str = "World"):168 # Some code here169```170171But `@app.command()` is just a decorator.172173That's equivalent to:174175```Python176def main(name: str = "World"):177 # Some code here178179decorator = app.command()180181new_main = decorator(main)182main = new_main183```184185`app.command()` returns a function (`decorator`) that takes another function as it's only parameter (`main`).186187And by using the `@something` you normally tell Python to replace the thing below (the function `main`) with the return of the `decorator` function (`new_main`).188189Now, in the specific case of **Typer**, the decorator doesn't change the original function. It registers it internally and returns it unmodified.190191So, `new_main` is actually the same original `main`.192193So, in the case of **Typer**, as it doesn't really modify the decorated function, that would be equivalent to:194195```Python196def main(name: str = "World"):197 # Some code here198199decorator = app.command()200201decorator(main)202```203204But then we don't need to create the variable `decorator` to use it below, we can just use it directly:205206```Python207def main(name: str = "World"):208 # Some code here209210app.command()(main)211```212213...that's it. It's still probably simpler to just create the explicit `typer.Typer` in the `main.py` file 😅.
modified:docs/alternatives.md+2 added-2 removed
22 unmodified lines
2324It inspired a lot of the ideas in **FastAPI** and **Typer**.2526!!! check "Inspired **Typer** to"27 Use function parameters to declare *CLI Arguments* and *CLI Options* as it simplifies a lot the development experience.27 Use function parameters to declare *CLI arguments* and *CLI options* as it simplifies a lot the development experience.2829### <a href="https://micheles.github.io/plac/" class="external-link" target="_blank">Plac</a>3031Plac is another library to create CLIs using parameters in functions, similar to Hug.
17 unmodified lines
49Click is one of the most widely used libraries to create CLIs in Python.5051It's a very powerful tool and there are many CLIs built with it. It is what powers **Typer** underneath.5253It also uses functions with parameters for *CLI Arguments* and *CLI Options*, but the declaration of the specific *CLI Arguments*, *CLI Options*, types, etc, is done in decorators on top of the function. This requires some code repetition (e.g. a *CLI Option* name `--verbose` and a variable name `verbose`) and synchronization between two places related to the same information (the decorator and the parameter function).53It also uses functions with parameters for *CLI arguments* and *CLI options*, but the declaration of the specific *CLI arguments*, *CLI options*, types, etc, is done in decorators on top of the function. This requires some code repetition (e.g. a *CLI Option* name `--verbose` and a variable name `verbose`) and synchronization between two places related to the same information (the decorator and the parameter function).5455It uses decorators on top of functions to modify the actual value of those functions, converting them to instances of a specific class. This is a clever trick, but code editors can't provide great support for autocompletion that way.5657It was built with some great ideas and design using the features available in the language at the time (Python 2.x).
26 unmodified lines
modified:docs/features.md+5 added-3 removed
1## Design based on **FastAPI**23<a href="https://fastapi.tiangolo.com" target="_blank"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" style="width: 20%;"></a>45**Typer** is <a href="https://fastapi.tiangolo.com" class="external-link" target="_blank">FastAPI</a>'s little sibling.65It follows the same design and ideas. If you know FastAPI, you already know **Typer**... more or less.7It follows the same design and ideas. If you know **FastAPI**, you already know **Typer**... more or less.89## Just Modern Python1011It's all based on standard **Python 3.6 type** declarations. No new syntax to learn. Just standard modern Python.
45 unmodified lines
5758 * `--install-completion`: Install completion for the current shell.59 * `--show-completion`: Show completion for the current shell, to copy it or customize the installation.6059 If you didn't add `shellingham` those *CLI Options* take a parameter with the name of the shell to install completion for, e.g.:61 If you didn't add `shellingham` those *CLI options* take a value with the name of the shell to install completion for, e.g.:62 63 * `--install-completion bash`.64 * `--show-completion powershell`.6566 Then you can tell the user to install completion after installing your CLI program and the rest will just work.6768!!! tip67 **Typer**'s completion is implemented internally, it uses ideas and components from Click and ideas from `click-completion`, but it doesn't use `click-completion` internally.69 **Typer**'s completion is implemented internally, it uses ideas and components from Click and ideas from `click-completion`, but it doesn't use `click-completion` and re-implements some of the relevant parts of Click.7071 Then it extends those ideas with features and bug fixes. For example, **Typer** programs also support modern versions of PowerShell (e.g. in Windows 10) among all the other shells.7273## The power of Click
16 unmodified lines
modified:docs/index.md+13 added-7 removed
22 unmodified lines
23**Source Code**: <a href="https://github.com/tiangolo/typer" target="_blank">https://github.com/tiangolo/typer</a>2425---2627Typer is library to build <abbr title="command line interface, programs executed from a terminal">CLI</abbr> applications that users will love using and developers will love creating. Based on Python 3.6+ type hints.27Typer is library for building <abbr title="command line interface, programs executed from a terminal">CLI</abbr> applications that users will **love using** and developers will **love creating**. Based on Python 3.6+ type hints.2829**Typer** is <a href="https://fastapi.tiangolo.com" class="external-link" target="_blank">FastAPI</a>'s little sibling. And it's intended to be the FastAPI of CLIs.3029The key features are:3031* **Intuitive to write**: Great editor support. <abbr title="also known as auto-complete, autocompletion, IntelliSense">Completion</abbr> everywhere. Less time debugging. Designed to be easy to use and learn. Less time reading docs.32* **Easy to use**: It's easy to use for the final users. Automatic help, and automatic completion for all shells.33* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.34* **Start simple**: The simplest example adds only 2 lines of code to your app: **1 import, 1 function call**.35* **Grow large**: Grow in complexity as much as you want, create arbitrarily complex trees of commands and groups of subcommands, with options and arguments.3637## FastAPI of CLIs3839<a href="https://fastapi.tiangolo.com" target="_blank"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" style="width: 20%;"></a>4041**Typer** is <a href="https://fastapi.tiangolo.com" class="external-link" target="_blank">FastAPI</a>'s little sibling.4243And it's intended to be the FastAPI of CLIs.4445## Requirements4647Python 3.6+4843Typer stands on the shoulders of a giant. Its only internal dependency is <a href="https://click.palletsprojects.com/" class="external-link" target="_blank">Click</a>.49**Typer** stands on the shoulders of a giant. Its only internal dependency is <a href="https://click.palletsprojects.com/" class="external-link" target="_blank">Click</a>.5051## Installation5253<div class="termy">
170 unmodified lines
224</div>225226### Recap227222In summary, you declare **once** the types of parameters (*arguments* and *options*) as function parameters.228In summary, you declare **once** the types of parameters (*CLI arguments* and *CLI options*) as function parameters.229230You do that with standard modern Python types.231232You don't have to learn a new syntax, the methods or classes of a specific library, etc.
30 unmodified lines
263 * Then you can use any tool you want to output your terminal's colors in all the systems, including the integrated `typer.style()` and `typer.secho()` (provided by Click).264 * Or any other tool, e.g. <a href="https://pypi.org/project/wasabi/" class="external-link" target="_blank"><code>wasabi</code></a>, <a href="https://github.com/erikrose/blessings" class="external-link" target="_blank"><code>blessings</code></a>.265* <a href="https://github.com/sarugaku/shellingham" class="external-link" target="_blank"><code>shellingham</code></a>: and Typer will automatically detect the current shell when installing completion.266 * With `shellingham` you can just use `--install-completion`.261 * Without `shellingham`, you have to pass a *CLI Option value* with the name of the shell to install completion, e.g. `--install-completion bash`.267 * Without `shellingham`, you have to pass the name of the shell to install completion for, e.g. `--install-completion bash`.268269You can install `typer` with `colorama` and `shellingham` with `pip install typer[all]`.270271## Other tools and plug-ins
3 unmodified lines
275For example:276277* <a href="https://github.com/click-contrib/click-spinner" class="external-link" target="_blank"><code>click-spinner</code></a>: to show the user that you are loading data. A Click plug-in.278 * There are several other Click plug-ins at <a href="https://github.com/click-contrib" class="external-link" target="_blank">click-contrib</a> that you can explore.273* <a href="https://pypi.org/project/tabulate/" class="external-link" target="_blank"><code>tabulate</code></a>: to automatically display tabular data nicely. Independent of Click or typer.279* <a href="https://pypi.org/project/tabulate/" class="external-link" target="_blank"><code>tabulate</code></a>: to automatically display tabular data nicely. Independent of Click or Typer.280* <a href="https://github.com/tqdm/tqdm" class="external-link" target="_blank"><code>tqdm</code></a>: a fast, extensible progress bar, alternative to Typer's own `typer.progressbar()`.281* etc... you can re-use many of the great available tools for building CLIs.282283## License
2 unmodified lines
modified:docs/typer-cli.md+1 added-1 removed
270 unmodified lines
271</div>272273## Options274275You can specify one of the following **CLI Options**:275You can specify one of the following **CLI options**:276277* `--app`: the name of the variable with a `Typer()` object to run as the main app.278* `--func`: the name of the variable with a function that would be used with `typer.run()`.279
152 unmodified lines
added:tests/assets/completion_no_types_order.py+23 added
1import typer23app = typer.Typer()456def complete(args, incomplete, ctx):7 typer.echo(f"info name is: {ctx.info_name}", err=True)8 typer.echo(f"args is: {args}", err=True)9 typer.echo(f"incomplete is: {incomplete}", err=True)10 return [11 ("Camila", "The reader of books."),12 ("Carlos", "The writer of scripts."),13 ("Sebastian", "The type hints guy."),14 ]151617@app.command()18def main(name: str = typer.Option("World", autocompletion=complete)):19 typer.echo(f"Hello {name}")202122if __name__ == "__main__":23 app()
added:tests/assets/completion_no_types.py+23 added
1import typer23app = typer.Typer()456def complete(ctx, args, incomplete):7 typer.echo(f"info name is: {ctx.info_name}", err=True)8 typer.echo(f"args is: {args}", err=True)9 typer.echo(f"incomplete is: {incomplete}", err=True)10 return [11 ("Camila", "The reader of books."),12 ("Carlos", "The writer of scripts."),13 ("Sebastian", "The type hints guy."),14 ]151617@app.command()18def main(name: str = typer.Option("World", autocompletion=complete)):19 typer.echo(f"Hello {name}")202122if __name__ == "__main__":23 app()
modified:tests/test_completion/test_completion.py+2 added-2 removed
14 unmodified lines
15 ],16 stdout=subprocess.PIPE,17 stderr=subprocess.PIPE,18 encoding="utf-8",19 env={**os.environ, "SHELL": "/bin/bash", "_TYPER_COMPLETE_TESTING": "True",},19 env={**os.environ, "SHELL": "/bin/bash", "_TYPER_COMPLETE_TESTING": "True"},20 )21 assert "_TUTORIAL001.PY_COMPLETE=complete_bash" in result.stdout2223
10 unmodified lines
34 ],35 stdout=subprocess.PIPE,36 stderr=subprocess.PIPE,37 encoding="utf-8",38 env={**os.environ, "SHELL": "/bin/bash", "_TYPER_COMPLETE_TESTING": "True",},38 env={**os.environ, "SHELL": "/bin/bash", "_TYPER_COMPLETE_TESTING": "True"},39 )40 new_text = bash_completion_path.read_text()41 bash_completion_path.write_text(text)42 assert 'eval "$(_TUTORIAL001.PY_COMPLETE=source_bash tutorial001.py)' in new_text
132 unmodified lines
added:tests/test_tutorial/test_commands/test_context/__init__.py
added:tests/test_tutorial/test_commands/test_context/test_tutorial001.py+32 added
1import subprocess2from commands.context import tutorial001 as mod34from typer.testing import CliRunner56app = mod.app78runner = CliRunner()91011def test_create():12 result = runner.invoke(app, ["create", "Camila"])13 assert result.exit_code == 014 assert "About to execute command: create" in result.output15 assert "Creating user: Camila" in result.output161718def test_delete():19 result = runner.invoke(app, ["delete", "Camila"])20 assert result.exit_code == 021 assert "About to execute command: delete" in result.output22 assert "Deleting 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_context/test_tutorial002.py+38 added
1import subprocess2from commands.context import tutorial002 as mod34from typer.testing import CliRunner56app = mod.app78runner = CliRunner()91011def test_create():12 result = runner.invoke(app, ["create", "Camila"])13 assert result.exit_code == 014 assert "Initializing database" in result.output15 assert "Creating user: Camila" in result.output161718def test_delete():19 result = runner.invoke(app, ["delete", "Camila"])20 assert result.exit_code == 021 assert "Initializing database" in result.output22 assert "Deleting user: Camila" in result.output232425def test_callback():26 result = runner.invoke(app)27 assert result.exit_code == 028 assert "Initializing database" 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_commands/test_context/test_tutorial003.py+38 added
1import subprocess2from commands.context import tutorial003 as mod34from typer.testing import CliRunner56app = mod.app78runner = CliRunner()91011def test_create():12 result = runner.invoke(app, ["create", "Camila"])13 assert result.exit_code == 014 assert "Initializing database" not in result.output15 assert "Creating user: Camila" in result.output161718def test_delete():19 result = runner.invoke(app, ["delete", "Camila"])20 assert result.exit_code == 021 assert "Initializing database" not in result.output22 assert "Deleting user: Camila" in result.output232425def test_callback():26 result = runner.invoke(app)27 assert result.exit_code == 028 assert "Initializing database" 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_commands/test_context/test_tutorial004.py+27 added
1import subprocess2from commands.context import tutorial004 as mod34from typer.testing import CliRunner56app = mod.app78runner = CliRunner()91011def test_1():12 result = runner.invoke(app, ["--name", "Camila", "--city", "Berlin"])13 assert result.exit_code == 014 assert "Got extra arg: --name" in result.output15 assert "Got extra arg: Camila" in result.output16 assert "Got extra arg: --city" in result.output17 assert "Got extra arg: Berlin" 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
modified:tests/test_tutorial/test_commands/test_help/test_tutorial001.py+3 added-3 removed
75 unmodified lines
76 assert "Operation cancelled" in result.output777879def test_delete_all():80 result = runner.invoke(app, ["delete-all",], input="y\n")80 result = runner.invoke(app, ["delete-all"], input="y\n")81 assert result.exit_code == 082 assert "Are you sure you want to delete ALL users? [y/N]:" in result.output83 assert "Deleting all users" in result.output848586def test_no_delete_all():87 result = runner.invoke(app, ["delete-all",], input="n\n")87 result = runner.invoke(app, ["delete-all"], input="n\n")88 assert result.exit_code == 089 assert "Are you sure you want to delete ALL users? [y/N]:" in result.output90 assert "Operation cancelled" in result.output919293def test_init():94 result = runner.invoke(app, ["init",])94 result = runner.invoke(app, ["init"])95 assert result.exit_code == 096 assert "Initializing user database" in result.output9798
8 unmodified lines
added:tests/test_tutorial/test_options/test_callback/__init__.py
added:tests/test_tutorial/test_options/test_callback/test_tutorial001.py+33 added
1import subprocess23import typer4from typer.testing import CliRunner56from options.callback import tutorial001 as mod78runner = CliRunner()910app = typer.Typer()11app.command()(mod.main)121314def test_1():15 result = runner.invoke(app, ["--name", "Camila"])16 assert result.exit_code == 017 assert "Hello Camila" in result.output181920def test_2():21 result = runner.invoke(app, ["--name", "rick"])22 assert result.exit_code != 023 assert "Error: Invalid value for '--name': Only Camila is allowed" 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
added:tests/test_tutorial/test_options/test_callback/test_tutorial003.py+52 added
1import os2import subprocess34import typer5from typer.testing import CliRunner67from options.callback import tutorial003 as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_1():16 result = runner.invoke(app, ["--name", "Camila"])17 assert result.exit_code == 018 assert "Validating name" in result.output19 assert "Hello Camila" in result.output202122def test_2():23 result = runner.invoke(app, ["--name", "rick"])24 assert result.exit_code != 025 assert "Error: Invalid value for '--name': Only Camila is allowed" in result.output262728def test_script():29 result = subprocess.run(30 ["coverage", "run", mod.__file__, "--help"],31 stdout=subprocess.PIPE,32 stderr=subprocess.PIPE,33 encoding="utf-8",34 )35 assert "Usage" in result.stdout363738def test_completion():39 result = subprocess.run(40 ["coverage", "run", mod.__file__, " "],41 stdout=subprocess.PIPE,42 stderr=subprocess.PIPE,43 encoding="utf-8",44 env={45 **os.environ,46 "_TUTORIAL003.PY_COMPLETE": "complete_bash",47 "COMP_WORDS": "tutorial003.py --",48 "COMP_CWORD": "1",49 "_TYPER_COMPLETE_TESTING": "True",50 },51 )52 assert "--name" in result.stdout
added:tests/test_tutorial/test_options/test_callback/test_tutorial004.py+52 added
1import os2import subprocess34import typer5from typer.testing import CliRunner67from options.callback import tutorial004 as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_1():16 result = runner.invoke(app, ["--name", "Camila"])17 assert result.exit_code == 018 assert "Validating param: name" in result.output19 assert "Hello Camila" in result.output202122def test_2():23 result = runner.invoke(app, ["--name", "rick"])24 assert result.exit_code != 025 assert "Error: Invalid value for '--name': Only Camila is allowed" in result.output262728def test_script():29 result = subprocess.run(30 ["coverage", "run", mod.__file__, "--help"],31 stdout=subprocess.PIPE,32 stderr=subprocess.PIPE,33 encoding="utf-8",34 )35 assert "Usage" in result.stdout363738def test_completion():39 result = subprocess.run(40 ["coverage", "run", mod.__file__, " "],41 stdout=subprocess.PIPE,42 stderr=subprocess.PIPE,43 encoding="utf-8",44 env={45 **os.environ,46 "_TUTORIAL004.PY_COMPLETE": "complete_bash",47 "COMP_WORDS": "tutorial004.py --",48 "COMP_CWORD": "1",49 "_TYPER_COMPLETE_TESTING": "True",50 },51 )52 assert "--name" in result.stdout
added:tests/test_tutorial/test_options/test_completion/__init__.py
added:tests/test_tutorial/test_options/test_completion/test_tutorial002.py+46 added
1import os2import subprocess34import typer5from typer.testing import CliRunner67from options.autocompletion import tutorial002 as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_completion():16 result = subprocess.run(17 ["coverage", "run", mod.__file__, " "],18 stdout=subprocess.PIPE,19 stderr=subprocess.PIPE,20 encoding="utf-8",21 env={22 **os.environ,23 "_TUTORIAL002.PY_COMPLETE": "complete_zsh",24 "_TYPER_COMPLETE_ARGS": "tutorial002.py --name ",25 "_TYPER_COMPLETE_TESTING": "True",26 },27 )28 assert "Camila" in result.stdout29 assert "Carlos" in result.stdout30 assert "Sebastian" in result.stdout313233def test_1():34 result = runner.invoke(app, ["--name", "Camila"])35 assert result.exit_code == 036 assert "Hello Camila" in result.output373839def test_script():40 result = subprocess.run(41 ["coverage", "run", mod.__file__, "--help"],42 stdout=subprocess.PIPE,43 stderr=subprocess.PIPE,44 encoding="utf-8",45 )46 assert "Usage" in result.stdout
added:tests/test_tutorial/test_options/test_completion/test_tutorial003.py+46 added
1import os2import subprocess34import typer5from typer.testing import CliRunner67from options.autocompletion import tutorial003 as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_completion():16 result = subprocess.run(17 ["coverage", "run", mod.__file__, " "],18 stdout=subprocess.PIPE,19 stderr=subprocess.PIPE,20 encoding="utf-8",21 env={22 **os.environ,23 "_TUTORIAL003.PY_COMPLETE": "complete_zsh",24 "_TYPER_COMPLETE_ARGS": "tutorial003.py --name Seb",25 "_TYPER_COMPLETE_TESTING": "True",26 },27 )28 assert "Camila" not in result.stdout29 assert "Carlos" not in result.stdout30 assert "Sebastian" in result.stdout313233def test_1():34 result = runner.invoke(app, ["--name", "Camila"])35 assert result.exit_code == 036 assert "Hello Camila" in result.output373839def test_script():40 result = subprocess.run(41 ["coverage", "run", mod.__file__, "--help"],42 stdout=subprocess.PIPE,43 stderr=subprocess.PIPE,44 encoding="utf-8",45 )46 assert "Usage" in result.stdout
added:tests/test_tutorial/test_options/test_completion/test_tutorial004.py+46 added
1import os2import subprocess34import typer5from typer.testing import CliRunner67from options.autocompletion import tutorial004 as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_completion():16 result = subprocess.run(17 ["coverage", "run", mod.__file__, " "],18 stdout=subprocess.PIPE,19 stderr=subprocess.PIPE,20 encoding="utf-8",21 env={22 **os.environ,23 "_TUTORIAL004.PY_COMPLETE": "complete_zsh",24 "_TYPER_COMPLETE_ARGS": "tutorial004.py --name ",25 "_TYPER_COMPLETE_TESTING": "True",26 },27 )28 assert '"Camila":"The reader of books."' in result.stdout29 assert '"Carlos":"The writer of scripts."' in result.stdout30 assert '"Sebastian":"The type hints guy."' in result.stdout313233def test_1():34 result = runner.invoke(app, ["--name", "Camila"])35 assert result.exit_code == 036 assert "Hello Camila" in result.output373839def test_script():40 result = subprocess.run(41 ["coverage", "run", mod.__file__, "--help"],42 stdout=subprocess.PIPE,43 stderr=subprocess.PIPE,44 encoding="utf-8",45 )46 assert "Usage" in result.stdout
added:tests/test_tutorial/test_options/test_completion/test_tutorial007.py+47 added
1import os2import subprocess34import typer5from typer.testing import CliRunner67from options.autocompletion import tutorial007 as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_completion():16 result = subprocess.run(17 ["coverage", "run", mod.__file__, " "],18 stdout=subprocess.PIPE,19 stderr=subprocess.PIPE,20 encoding="utf-8",21 env={22 **os.environ,23 "_TUTORIAL007.PY_COMPLETE": "complete_zsh",24 "_TYPER_COMPLETE_ARGS": "tutorial007.py --name Sebastian --name ",25 "_TYPER_COMPLETE_TESTING": "True",26 },27 )28 assert '"Camila":"The reader of books."' in result.stdout29 assert '"Carlos":"The writer of scripts."' in result.stdout30 assert '"Sebastian":"The type hints guy."' not in result.stdout313233def test_1():34 result = runner.invoke(app, ["--name", "Camila", "--name", "Sebastian"])35 assert result.exit_code == 036 assert "Hello Camila" in result.output37 assert "Hello Sebastian" 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_options/test_completion/test_tutorial008.py+48 added
1import os2import subprocess34import typer5from typer.testing import CliRunner67from options.autocompletion import tutorial008 as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_completion():16 result = subprocess.run(17 ["coverage", "run", mod.__file__, " "],18 stdout=subprocess.PIPE,19 stderr=subprocess.PIPE,20 encoding="utf-8",21 env={22 **os.environ,23 "_TUTORIAL008.PY_COMPLETE": "complete_zsh",24 "_TYPER_COMPLETE_ARGS": "tutorial008.py --name ",25 "_TYPER_COMPLETE_TESTING": "True",26 },27 )28 assert '"Camila":"The reader of books."' in result.stdout29 assert '"Carlos":"The writer of scripts."' in result.stdout30 assert '"Sebastian":"The type hints guy."' in result.stdout31 assert "['--name']" in result.stderr323334def test_1():35 result = runner.invoke(app, ["--name", "Camila", "--name", "Sebastian"])36 assert result.exit_code == 037 assert "Hello Camila" in result.output38 assert "Hello Sebastian" in result.output394041def test_script():42 result = subprocess.run(43 ["coverage", "run", mod.__file__, "--help"],44 stdout=subprocess.PIPE,45 stderr=subprocess.PIPE,46 encoding="utf-8",47 )48 assert "Usage" in result.stdout
added:tests/test_tutorial/test_options/test_completion/test_tutorial009.py+48 added
1import os2import subprocess34import typer5from typer.testing import CliRunner67from options.autocompletion import tutorial009 as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_completion():16 result = subprocess.run(17 ["coverage", "run", mod.__file__, " "],18 stdout=subprocess.PIPE,19 stderr=subprocess.PIPE,20 encoding="utf-8",21 env={22 **os.environ,23 "_TUTORIAL009.PY_COMPLETE": "complete_zsh",24 "_TYPER_COMPLETE_ARGS": "tutorial009.py --name Sebastian --name ",25 "_TYPER_COMPLETE_TESTING": "True",26 },27 )28 assert '"Camila":"The reader of books."' in result.stdout29 assert '"Carlos":"The writer of scripts."' in result.stdout30 assert '"Sebastian":"The type hints guy."' not in result.stdout31 assert "['--name', 'Sebastian', '--name']" in result.stderr323334def test_1():35 result = runner.invoke(app, ["--name", "Camila", "--name", "Sebastian"])36 assert result.exit_code == 037 assert "Hello Camila" in result.output38 assert "Hello Sebastian" in result.output394041def test_script():42 result = subprocess.run(43 ["coverage", "run", mod.__file__, "--help"],44 stdout=subprocess.PIPE,45 stderr=subprocess.PIPE,46 encoding="utf-8",47 )48 assert "Usage" in result.stdout
added:tests/test_tutorial/test_options/test_version/__init__.py
added:tests/test_tutorial/test_options/test_version/test_tutorial003.py+57 added
1import os2import subprocess34import typer5from typer.testing import CliRunner67from options.version import tutorial003 as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_1():16 result = runner.invoke(app, ["--name", "Rick", "--version"])17 assert result.exit_code == 018 assert "Awesome CLI Version: 0.1.0" in result.output192021def test_2():22 result = runner.invoke(app, ["--name", "rick"])23 assert result.exit_code != 024 assert "Error: Invalid value for '--name': Only Camila is allowed" in result.output252627def test_3():28 result = runner.invoke(app, ["--name", "Camila"])29 assert result.exit_code == 030 assert "Hello Camila" in result.output313233def test_script():34 result = subprocess.run(35 ["coverage", "run", mod.__file__, "--help"],36 stdout=subprocess.PIPE,37 stderr=subprocess.PIPE,38 encoding="utf-8",39 )40 assert "Usage" in result.stdout414243def test_completion():44 result = subprocess.run(45 ["coverage", "run", mod.__file__, " "],46 stdout=subprocess.PIPE,47 stderr=subprocess.PIPE,48 encoding="utf-8",49 env={50 **os.environ,51 "_TUTORIAL003.PY_COMPLETE": "complete_bash",52 "COMP_WORDS": "tutorial003.py --name Rick --v",53 "COMP_CWORD": "3",54 "_TYPER_COMPLETE_TESTING": "True",55 },56 )57 assert "--version" in result.stdout
added:tests/test_tutorial/test_testing/__init__.py
added:tests/test_tutorial/test_testing/test_app01.py+18 added
1import subprocess23from testing.app01 import main as mod4from testing.app01.test_main import test_app567def test_app01():8 test_app()91011def test_script():12 result = subprocess.run(13 ["coverage", "run", mod.__file__, "--help"],14 stdout=subprocess.PIPE,15 stderr=subprocess.PIPE,16 encoding="utf-8",17 )18 assert "Usage" in result.stdout
added:tests/test_tutorial/test_testing/test_app02.py+18 added
1import subprocess23from testing.app02 import main as mod4from testing.app02.test_main import test_app567def test_app02():8 test_app()91011def test_script():12 result = subprocess.run(13 ["coverage", "run", mod.__file__, "--help"],14 stdout=subprocess.PIPE,15 stderr=subprocess.PIPE,16 encoding="utf-8",17 )18 assert "Usage" in result.stdout
added:tests/test_tutorial/test_testing/test_app03.py+18 added
1import subprocess23from testing.app03 import main as mod4from testing.app03.test_main import test_app567def test_app03():8 test_app()91011def test_script():12 result = subprocess.run(13 ["coverage", "run", mod.__file__, "--help"],14 stdout=subprocess.PIPE,15 stderr=subprocess.PIPE,16 encoding="utf-8",17 )18 assert "Usage" in result.stdout
modified:tests/test_others.py+131 added-1 removed
1import os2import subprocess3from pathlib import Path4from typing import Optional5from unittest import mock67import click8import pytest9import shellingham10import typer11import typer.completion12from typer.main import solve_typer_info_defaults, solve_typer_info_help
52 unmodified lines
65 @app.command()66 def main():67 typer.echo("Hello World")6864 typer.completion.Shells69 with mock.patch.object(70 shellingham, "detect_shell", return_value=("xshell", "/usr/bin/xshell")71 ):72 result = runner.invoke(app, ["--install-completion"])73 assert "Shell xshell is not supported." in result.stdout74 result = runner.invoke(app)75 assert "Hello World" in result.stdout767778def test_callback_too_many_parameters():79 app = typer.Typer()8081 def name_callback(ctx, param, val1, val2):82 pass # pragma: nocover8384 @app.command()85 def main(name: str = typer.Option(..., callback=name_callback)):86 pass # pragma: nocover8788 with pytest.raises(click.ClickException) as exc_info:89 runner.invoke(app, ["--name", "Camila"])90 assert (91 exc_info.value.message == "Too many CLI parameter callback function parameters"92 )939495def test_callback_2_untyped_parameters():96 app = typer.Typer()9798 def name_callback(ctx, value):99 typer.echo(f"info name is: {ctx.info_name}")100 typer.echo(f"value is: {value}")101102 @app.command()103 def main(name: str = typer.Option(..., callback=name_callback)):104 typer.echo("Hello World")105106 result = runner.invoke(app, ["--name", "Camila"])107 assert "info name is: main" in result.stdout108 assert "value is: Camila" in result.stdout109110111def test_callback_3_untyped_parameters():112 app = typer.Typer()113114 def name_callback(ctx, param, value):115 typer.echo(f"info name is: {ctx.info_name}")116 typer.echo(f"param name is: {param.name}")117 typer.echo(f"value is: {value}")118119 @app.command()120 def main(name: str = typer.Option(..., callback=name_callback)):121 typer.echo("Hello World")122123 result = runner.invoke(app, ["--name", "Camila"])124 assert "info name is: main" in result.stdout125 assert "param name is: name" in result.stdout126 assert "value is: Camila" in result.stdout127128129def test_completion_untyped_parameters():130 file_path = Path(__file__).parent / "assets/completion_no_types.py"131 result = subprocess.run(132 ["coverage", "run", str(file_path)],133 stdout=subprocess.PIPE,134 stderr=subprocess.PIPE,135 encoding="utf-8",136 env={137 **os.environ,138 "_COMPLETION_NO_TYPES.PY_COMPLETE": "complete_zsh",139 "_TYPER_COMPLETE_ARGS": "completion_no_types.py --name Sebastian --name Ca",140 "_TYPER_COMPLETE_TESTING": "True",141 },142 )143 assert "info name is: completion_no_types.py" in result.stderr144 assert "args is: ['--name', 'Sebastian', '--name']" in result.stderr145 assert "incomplete is: Ca" in result.stderr146 assert '"Camila":"The reader of books."' in result.stdout147 assert '"Carlos":"The writer of scripts."' in result.stdout148 assert '"Sebastian":"The type hints guy."' in result.stdout149150 result = subprocess.run(151 ["coverage", "run", str(file_path)],152 stdout=subprocess.PIPE,153 stderr=subprocess.PIPE,154 encoding="utf-8",155 )156 assert "Hello World" in result.stdout157158159def test_completion_untyped_parameters_different_order_correct_names():160 file_path = Path(__file__).parent / "assets/completion_no_types_order.py"161 result = subprocess.run(162 ["coverage", "run", str(file_path)],163 stdout=subprocess.PIPE,164 stderr=subprocess.PIPE,165 encoding="utf-8",166 env={167 **os.environ,168 "_COMPLETION_NO_TYPES_ORDER.PY_COMPLETE": "complete_zsh",169 "_TYPER_COMPLETE_ARGS": "completion_no_types_order.py --name Sebastian --name Ca",170 "_TYPER_COMPLETE_TESTING": "True",171 },172 )173 assert "info name is: completion_no_types_order.py" in result.stderr174 assert "args is: ['--name', 'Sebastian', '--name']" in result.stderr175 assert "incomplete is: Ca" in result.stderr176 assert '"Camila":"The reader of books."' in result.stdout177 assert '"Carlos":"The writer of scripts."' in result.stdout178 assert '"Sebastian":"The type hints guy."' in result.stdout179180 result = subprocess.run(181 ["coverage", "run", str(file_path)],182 stdout=subprocess.PIPE,183 stderr=subprocess.PIPE,184 encoding="utf-8",185 )186 assert "Hello World" in result.stdout187188189def test_autocompletion_too_many_parameters():190 app = typer.Typer()191192 def name_callback(ctx, args, incomplete, val2):193 pass # pragma: nocover194195 @app.command()196 def main(name: str = typer.Option(..., autocompletion=name_callback)):197 pass # pragma: nocover198199 with pytest.raises(click.ClickException) as exc_info:200 runner.invoke(app, ["--name", "Camila"])201 assert exc_info.value.message == "Invalid autocompletion callback parameters: val2"
modified:typer/__init__.py+9 added-2 removed
1"""Typer, build great CLIs. Easy to code. Based on Python type hints."""23__version__ = "0.0.11"45from click.exceptions import Abort, Exit5from click.exceptions import Abort, BadParameter, Exit6from click.termui import (7 clear,8 confirm,9 echo_via_pager,
18 unmodified lines
28)2930from . import colors31from .main import Typer, run32from .models import Context, FileBinaryRead, FileBinaryWrite, FileText, FileTextWrite32from .models import (33 CallbackParam,34 Context,35 FileBinaryRead,36 FileBinaryWrite,37 FileText,38 FileTextWrite,39)40from .params import Argument, Option
modified:typer/main.py+112 added-5 removed
319 unmodified lines
320 except AttributeError:321 pass322 # Priority 3: Value set in subapp = typer.Typer()323 try:324 instance_value = getattr(typer_info.typer_instance.info, name) # type: ignore324 instance_value = getattr(325 typer_info.typer_instance.info, name # type: ignore326 )327 if not isinstance(instance_value, DefaultPlaceholder):328 values[name] = instance_value329 continue330 except AttributeError:
368 unmodified lines
699 show_envvar=parameter_info.show_envvar,700 # Parameter701 required=required,702 default=default_value,701 callback=parameter_info.callback,703 callback=get_param_callback(704 callback=parameter_info.callback, convertor=convertor705 ),706 metavar=parameter_info.metavar,707 expose_value=parameter_info.expose_value,708 is_eager=parameter_info.is_eager,709 envvar=parameter_info.envvar,706 autocompletion=parameter_info.autocompletion,710 autocompletion=get_param_completion(parameter_info.autocompletion),711 ),712 convertor,713 )714 elif isinstance(parameter_info, ArgumentInfo):
9 unmodified lines
724 required=required,725 nargs=nargs,726 # Parameter727 default=default_value,724 callback=parameter_info.callback,728 callback=get_param_callback(729 callback=parameter_info.callback, convertor=convertor730 ),731 metavar=parameter_info.metavar,732 expose_value=parameter_info.expose_value,733 is_eager=parameter_info.is_eager,734 envvar=parameter_info.envvar,729 autocompletion=parameter_info.autocompletion,735 autocompletion=get_param_completion(parameter_info.autocompletion),736 ),737 convertor,738 )739 assert False, "A click.Parameter should be returned" # pragma no cover740741742def get_param_callback(743 *, callback: Optional[Callable] = None, convertor: Optional[Callable] = None744) -> Optional[Callable]:745 if not callback:746 return None747 signature = inspect.signature(callback)748 ctx_name = None749 click_param_name = None750 value_name = None751 untyped_names: List[str] = []752 for param_name, param_sig in signature.parameters.items():753 if lenient_issubclass(param_sig.annotation, click.Context):754 ctx_name = param_name755 elif lenient_issubclass(param_sig.annotation, click.Parameter):756 click_param_name = param_name757 else:758 untyped_names.append(param_name)759 # Extract value param name first760 if untyped_names:761 value_name = untyped_names.pop()762 # If context and Click param were not typed (old/Click callback style) extract them763 if untyped_names:764 if ctx_name is None:765 ctx_name = untyped_names.pop(0)766 if click_param_name is None:767 if untyped_names:768 click_param_name = untyped_names.pop(0)769 if untyped_names:770 raise click.ClickException(771 "Too many CLI parameter callback function parameters"772 )773774 def wrapper(ctx: click.Context, param: click.Parameter, value: Any) -> Any:775 use_params: Dict[str, Any] = {}776 if ctx_name:777 use_params[ctx_name] = ctx778 if click_param_name:779 use_params[click_param_name] = param780 if value_name:781 if convertor:782 use_value = convertor(value)783 else:784 use_value = value785 use_params[value_name] = use_value786 return callback(**use_params) # type: ignore787788 update_wrapper(wrapper, callback)789 return wrapper790791792def get_param_completion(callback: Optional[Callable] = None) -> Optional[Callable]:793 if not callback:794 return None795 signature = inspect.signature(callback)796 ctx_name = None797 args_name = None798 incomplete_name = None799 unassigned_params = [param for param in signature.parameters.values()]800 for param_sig in unassigned_params[:]:801 origin = getattr(param_sig.annotation, "__origin__", None)802 if lenient_issubclass(param_sig.annotation, click.Context):803 ctx_name = param_sig.name804 unassigned_params.remove(param_sig)805 elif lenient_issubclass(origin, List):806 args_name = param_sig.name807 unassigned_params.remove(param_sig)808 elif lenient_issubclass(param_sig.annotation, str):809 incomplete_name = param_sig.name810 unassigned_params.remove(param_sig)811 # If there are still unassigned parameters (not typed), extract by name812 for param_sig in unassigned_params[:]:813 if ctx_name is None and param_sig.name == "ctx":814 ctx_name = param_sig.name815 unassigned_params.remove(param_sig)816 elif args_name is None and param_sig.name == "args":817 args_name = param_sig.name818 unassigned_params.remove(param_sig)819 elif incomplete_name is None and param_sig.name == "incomplete":820 incomplete_name = param_sig.name821 unassigned_params.remove(param_sig)822 # Extract value param name first823 if unassigned_params:824 show_params = " ".join([param.name for param in unassigned_params])825 raise click.ClickException(826 f"Invalid autocompletion callback parameters: {show_params}"827 )828829 def wrapper(ctx: click.Context, args: List[str], incomplete: Optional[str]) -> Any:830 use_params: Dict[str, Any] = {}831 if ctx_name:832 use_params[ctx_name] = ctx833 if args_name:834 use_params[args_name] = args835 if incomplete_name:836 use_params[incomplete_name] = incomplete837 return callback(**use_params) # type: ignore838839 update_wrapper(wrapper, callback)840 return wrapper841842843def run(function: Callable) -> Any:844 app = Typer()845 app.command()(function)846 app()
modified:typer/models.py+12 added-14 removed
43 unmodified lines
44class FileBinaryWrite(io.BufferedWriter):45 pass464748class CallbackParam(click.Parameter):49 pass505152class DefaultPlaceholder:53 """54 You shouldn't use this class directly.55
29 unmodified lines
85 name: Optional[str] = None,86 *,87 cls: Optional[Type[click.Command]] = None,88 context_settings: Optional[Dict[Any, Any]] = None,85 callback: Optional[Callable[..., Any]] = None,89 callback: Optional[Callable] = None,90 help: Optional[str] = None,91 epilog: Optional[str] = None,92 short_help: Optional[str] = None,93 options_metavar: str = "[OPTIONS]",
29 unmodified lines
123 chain: bool = Default(False),124 result_callback: Optional[Callable] = Default(None),125 # Command126 context_settings: Optional[Dict[Any, Any]] = Default(None),123 callback: Optional[Callable[..., Any]] = Default(None),127 callback: Optional[Callable] = Default(None),128 help: Optional[str] = Default(None),129 epilog: Optional[str] = Default(None),130 short_help: Optional[str] = Default(None),131 options_metavar: str = Default("[OPTIONS]"),
25 unmodified lines
157 self,158 *,159 default: Optional[Any] = None,160 param_decls: Optional[Sequence[str]] = None,157 callback: Optional[Callable[[click.Context, click.Parameter, str], Any]] = None,161 callback: Optional[Callable] = None,162 metavar: Optional[str] = None,163 expose_value: bool = True,164 is_eager: bool = False,165 envvar: Optional[Union[str, List[str]]] = None,162 autocompletion: Optional[163 Callable[[click.Context, List[str], str], List[str]]164 ] = None,166 autocompletion: Optional[Callable] = None,167 # Choice168 case_sensitive: bool = True,169 # Numbers170 min: Optional[Union[int, float]] = None,
56 unmodified lines
227 *,228 # ParameterInfo229 default: Optional[Any] = None,230 param_decls: Optional[Sequence[str]] = None,229 callback: Optional[Callable[[click.Context, click.Parameter, str], Any]] = None,231 callback: Optional[Callable] = None,232 metavar: Optional[str] = None,233 expose_value: bool = True,234 is_eager: bool = False,235 envvar: Optional[Union[str, List[str]]] = None,234 autocompletion: Optional[235 Callable[[click.Context, List[str], str], List[str]]236 ] = None,236 autocompletion: Optional[Callable] = None,237 # Option238 show_default: bool = False,239 prompt: Union[bool, str] = False,240 confirmation_prompt: bool = False,
83 unmodified lines
324 *,325 # ParameterInfo326 default: Optional[Any] = None,327 param_decls: Optional[Sequence[str]] = None,328 callback: Optional[Callable[[click.Context, click.Parameter, str], Any]] = None,328 callback: Optional[Callable] = None,329 metavar: Optional[str] = None,330 expose_value: bool = True,331 is_eager: bool = False,332 envvar: Optional[Union[str, List[str]]] = None,333 autocompletion: Optional[334 Callable[[click.Context, List[str], str], List[str]]335 ] = None,333 autocompletion: Optional[Callable] = None,334 # Choice335 case_sensitive: bool = True,336 # Numbers337 min: Optional[Union[int, float]] = None,
53 unmodified lines
modified:typer/params.py+4 added-10 removed
1from typing import Any, Callable, List, Optional, Type, Union23import click43from .models import ArgumentInfo, OptionInfo456def Option(7 # Parameter8 default: Optional[Any],9 *param_decls: str,12 callback: Optional[Callable[[click.Context, click.Parameter, str], Any]] = None,10 callback: Optional[Callable] = None,11 metavar: Optional[str] = None,12 expose_value: bool = True,13 is_eager: bool = False,14 envvar: Optional[Union[str, List[str]]] = None,17 autocompletion: Optional[18 Callable[[click.Context, List[str], str], List[str]]19 ] = None,15 autocompletion: Optional[Callable] = None,16 # Option17 show_default: bool = False,18 prompt: Union[bool, str] = False,19 confirmation_prompt: bool = False,
82 unmodified lines
102def Argument(103 # Parameter104 default: Optional[Any],105 *,110 callback: Optional[Callable[[click.Context, click.Parameter, str], Any]] = None,106 callback: Optional[Callable] = None,107 metavar: Optional[str] = None,108 expose_value: bool = True,109 is_eager: bool = False,110 envvar: Optional[Union[str, List[str]]] = None,115 autocompletion: Optional[116 Callable[[click.Context, List[str], str], List[str]]117 ] = None,111 autocompletion: Optional[Callable] = None,112 # Choice113 case_sensitive: bool = True,114 # Numbers115 min: Optional[Union[int, float]] = None,
56 unmodified lines
modified:mkdocs.yml+6 added
29 unmodified lines
30 - CLI Options Intro: 'tutorial/options/index.md'31 - CLI Options with Help: 'tutorial/options/help.md'32 - Required CLI Options: 'tutorial/options/required.md'33 - CLI Option Prompt: 'tutorial/options/prompt.md'34 - Password CLI Option and Confirmation Prompt: 'tutorial/options/password.md'35 - CLI Option Name: 'tutorial/options/name.md'36 - CLI Option Callback and Context: 'tutorial/options/callback-and-context.md'37 - Version CLI Option, is_eager: 'tutorial/options/version.md'38 - CLI Option autocompletion: 'tutorial/options/autocompletion.md'39 - Commands:40 - Commands Intro: 'tutorial/commands/index.md'41 - Command CLI Arguments: 'tutorial/commands/arguments.md'42 - Command CLI Options: 'tutorial/commands/options.md'43 - Command Help: 'tutorial/commands/help.md'44 - Custom Command Name: 'tutorial/commands/name.md'45 - Typer Callback: 'tutorial/commands/callback.md'46 - One or Multiple Commands: 'tutorial/commands/one-or-multiple.md'47 - Using the Context: 'tutorial/commands/context.md'48 - CLI Parameter Types:49 - CLI Parameter Types Intro: 'tutorial/parameter-types/index.md'50 - Number: 'tutorial/parameter-types/number.md'51 - Boolean CLI Options: 'tutorial/parameter-types/bool.md'
17 unmodified lines
69 - Ask with Prompt: 'tutorial/prompt.md'70 - Progress Bar: 'tutorial/progressbar.md'71 - CLI Application Directory: 'tutorial/app-dir.md'72 - Launching Applications: 'tutorial/launch.md'73 - Testing: 'tutorial/testing.md'74 - Typer CLI - completion for small scripts: 'typer-cli.md'75 - Alternatives, Inspiration and Comparisons: 'alternatives.md'76 - Help Typer - Get Help: 'help-typer.md'77 - Development - Contributing: 'contributing.md'
41 unmodified lines
modified:mypy.ini+2 added-3 removed
1[mypy]2ignore_missing_imports = True3disallow_untyped_defs = True35[mypy-tests.*]6disallow_untyped_defs = False4[mypy-typer.*]5disallow_untyped_defs = True
modified:pyproject.toml+4 added
50 unmodified lines
51 "mkdocs",52 "mkdocs-material",53 "markdown-include"54]55dev = [56 "autoflake",57 "flake8",58]59all = [60 "colorama",61 "shellingham"62]
modified:README.md+13 added-7 removed
22 unmodified lines
23**Source Code**: <a href="https://github.com/tiangolo/typer" target="_blank">https://github.com/tiangolo/typer</a>2425---2627Typer is library to build <abbr title="command line interface, programs executed from a terminal">CLI</abbr> applications that users will love using and developers will love creating. Based on Python 3.6+ type hints.27Typer is library for building <abbr title="command line interface, programs executed from a terminal">CLI</abbr> applications that users will **love using** and developers will **love creating**. Based on Python 3.6+ type hints.2829**Typer** is <a href="https://fastapi.tiangolo.com" class="external-link" target="_blank">FastAPI</a>'s little sibling. And it's intended to be the FastAPI of CLIs.3029The key features are:3031* **Intuitive to write**: Great editor support. <abbr title="also known as auto-complete, autocompletion, IntelliSense">Completion</abbr> everywhere. Less time debugging. Designed to be easy to use and learn. Less time reading docs.32* **Easy to use**: It's easy to use for the final users. Automatic help, and automatic completion for all shells.33* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.34* **Start simple**: The simplest example adds only 2 lines of code to your app: **1 import, 1 function call**.35* **Grow large**: Grow in complexity as much as you want, create arbitrarily complex trees of commands and groups of subcommands, with options and arguments.3637## FastAPI of CLIs3839<a href="https://fastapi.tiangolo.com" target="_blank"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" style="width: 20%;"></a>4041**Typer** is <a href="https://fastapi.tiangolo.com" class="external-link" target="_blank">FastAPI</a>'s little sibling.4243And it's intended to be the FastAPI of CLIs.4445## Requirements4647Python 3.6+4843Typer stands on the shoulders of a giant. Its only internal dependency is <a href="https://click.palletsprojects.com/" class="external-link" target="_blank">Click</a>.49**Typer** stands on the shoulders of a giant. Its only internal dependency is <a href="https://click.palletsprojects.com/" class="external-link" target="_blank">Click</a>.5051## Installation5253<div class="termy">
170 unmodified lines
224</div>225226### Recap227222In summary, you declare **once** the types of parameters (*arguments* and *options*) as function parameters.228In summary, you declare **once** the types of parameters (*CLI arguments* and *CLI options*) as function parameters.229230You do that with standard modern Python types.231232You don't have to learn a new syntax, the methods or classes of a specific library, etc.
30 unmodified lines
263 * Then you can use any tool you want to output your terminal's colors in all the systems, including the integrated `typer.style()` and `typer.secho()` (provided by Click).264 * Or any other tool, e.g. <a href="https://pypi.org/project/wasabi/" class="external-link" target="_blank"><code>wasabi</code></a>, <a href="https://github.com/erikrose/blessings" class="external-link" target="_blank"><code>blessings</code></a>.265* <a href="https://github.com/sarugaku/shellingham" class="external-link" target="_blank"><code>shellingham</code></a>: and Typer will automatically detect the current shell when installing completion.266 * With `shellingham` you can just use `--install-completion`.261 * Without `shellingham`, you have to pass a *CLI Option value* with the name of the shell to install completion, e.g. `--install-completion bash`.267 * Without `shellingham`, you have to pass the name of the shell to install completion for, e.g. `--install-completion bash`.268269You can install `typer` with `colorama` and `shellingham` with `pip install typer[all]`.270271## Other tools and plug-ins
3 unmodified lines
275For example:276277* <a href="https://github.com/click-contrib/click-spinner" class="external-link" target="_blank"><code>click-spinner</code></a>: to show the user that you are loading data. A Click plug-in.278 * There are several other Click plug-ins at <a href="https://github.com/click-contrib" class="external-link" target="_blank">click-contrib</a> that you can explore.273* <a href="https://pypi.org/project/tabulate/" class="external-link" target="_blank"><code>tabulate</code></a>: to automatically display tabular data nicely. Independent of Click or typer.279* <a href="https://pypi.org/project/tabulate/" class="external-link" target="_blank"><code>tabulate</code></a>: to automatically display tabular data nicely. Independent of Click or Typer.280* <a href="https://github.com/tqdm/tqdm" class="external-link" target="_blank"><code>tqdm</code></a>: a fast, extensible progress bar, alternative to Typer's own `typer.progressbar()`.281* etc... you can re-use many of the great available tools for building CLIs.282283## License
2 unmodified lines