: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
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
Provenance
- Commit
5a6379f- Tree
493a160- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
eec98ba
88 files changed+2760 added−83 removed
added:docs/src/commands/context/tutorial001.py+25 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command()7+def create(username: str):8+ typer.echo(f"Creating user: {username}")9+10+11+@app.command()12+def delete(username: str):13+ typer.echo(f"Deleting user: {username}")14+15+16+@app.callback()17+def 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}")22+23+24+if __name__ == "__main__":25+ app()added:docs/src/commands/context/tutorial002.py+25 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command()7+def create(username: str):8+ typer.echo(f"Creating user: {username}")9+10+11+@app.command()12+def delete(username: str):13+ typer.echo(f"Deleting user: {username}")14+15+16+@app.callback(invoke_without_command=True)17+def main():18+ """19+ Manage users in the awesome CLI app.20+ """21+ typer.echo("Initializing database")22+23+24+if __name__ == "__main__":25+ app()added:docs/src/commands/context/tutorial003.py+26 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command()7+def create(username: str):8+ typer.echo(f"Creating user: {username}")9+10+11+@app.command()12+def delete(username: str):13+ typer.echo(f"Deleting user: {username}")14+15+16+@app.callback(invoke_without_command=True)17+def 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")23+24+25+if __name__ == "__main__":26+ app()added:docs/src/commands/context/tutorial004.py+15 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command(7+ context_settings={"allow_extra_args": True, "ignore_unknown_options": True}8+)9+def main(ctx: typer.Context):10+ for extra_arg in ctx.args:11+ typer.echo(f"Got extra arg: {extra_arg}")12+13+14+if __name__ == "__main__":15+ app()added:docs/src/options/autocompletion/tutorial001.py+9 added
1+import typer2+3+4+def main(name: str = typer.Option("World", help="The name to say hi to.")):5+ typer.echo(f"Hello {name}")6+7+8+if __name__ == "__main__":9+ typer.run(main)added:docs/src/options/autocompletion/tutorial002.py+17 added
1+import typer2+3+4+def complete_name():5+ return ["Camila", "Carlos", "Sebastian"]6+7+8+def 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}")14+15+16+if __name__ == "__main__":17+ typer.run(main)added:docs/src/options/autocompletion/tutorial003.py+23 added
1+import typer2+3+valid_names = ["Camila", "Carlos", "Sebastian"]4+5+6+def complete_name(incomplete: str):7+ completion = []8+ for name in valid_names:9+ if name.startswith(incomplete):10+ completion.append(name)11+ return completion12+13+14+def 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}")20+21+22+if __name__ == "__main__":23+ typer.run(main)added:docs/src/options/autocompletion/tutorial004.py+28 added
1+import typer2+3+valid_completion_items = [4+ ("Camila", "The reader of books."),5+ ("Carlos", "The writer of scripts."),6+ ("Sebastian", "The type hints guy."),7+]8+9+10+def 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 completion17+18+19+def 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}")25+26+27+if __name__ == "__main__":28+ typer.run(main)added:docs/src/options/autocompletion/tutorial005.py+25 added
1+import typer2+3+valid_completion_items = [4+ ("Camila", "The reader of books."),5+ ("Carlos", "The writer of scripts."),6+ ("Sebastian", "The type hints guy."),7+]8+9+10+def complete_name(incomplete: str):11+ for name, help_text in valid_completion_items:12+ if name.startswith(incomplete):13+ yield (name, help_text)14+15+16+def 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}")22+23+24+if __name__ == "__main__":25+ typer.run(main)added:docs/src/options/autocompletion/tutorial006.py+12 added
1+from typing import List2+3+import typer4+5+6+def 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}")9+10+11+if __name__ == "__main__":12+ typer.run(main)added:docs/src/options/autocompletion/tutorial007.py+29 added
1+from typing import List2+3+import typer4+5+valid_completion_items = [6+ ("Camila", "The reader of books."),7+ ("Carlos", "The writer of scripts."),8+ ("Sebastian", "The type hints guy."),9+]10+11+12+def 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)17+18+19+def 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}")26+27+28+if __name__ == "__main__":29+ typer.run(main)added:docs/src/options/autocompletion/tutorial008.py+29 added
1+from typing import List2+3+import typer4+5+valid_completion_items = [6+ ("Camila", "The reader of books."),7+ ("Carlos", "The writer of scripts."),8+ ("Sebastian", "The type hints guy."),9+]10+11+12+def 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)17+18+19+def 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}")26+27+28+if __name__ == "__main__":29+ typer.run(main)added:docs/src/options/autocompletion/tutorial009.py+30 added
1+from typing import List2+3+import typer4+5+valid_completion_items = [6+ ("Camila", "The reader of books."),7+ ("Carlos", "The writer of scripts."),8+ ("Sebastian", "The type hints guy."),9+]10+11+12+def 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)18+19+20+def 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}")27+28+29+if __name__ == "__main__":30+ typer.run(main)added:docs/src/options/callback/tutorial001.py+15 added
1+import typer2+3+4+def name_callback(value: str):5+ if value != "Camila":6+ raise typer.BadParameter("Only Camila is allowed")7+ return value8+9+10+def main(name: str = typer.Option(..., callback=name_callback)):11+ typer.echo(f"Hello {name}")12+13+14+if __name__ == "__main__":15+ typer.run(main)added:docs/src/options/callback/tutorial002.py+16 added
1+import typer2+3+4+def name_callback(value: str):5+ typer.echo("Validating name")6+ if value != "Camila":7+ raise typer.BadParameter("Only Camila is allowed")8+ return value9+10+11+def main(name: str = typer.Option(..., callback=name_callback)):12+ typer.echo(f"Hello {name}")13+14+15+if __name__ == "__main__":16+ typer.run(main)added:docs/src/options/callback/tutorial003.py+18 added
1+import typer2+3+4+def 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 value11+12+13+def main(name: str = typer.Option(..., callback=name_callback)):14+ typer.echo(f"Hello {name}")15+16+17+if __name__ == "__main__":18+ typer.run(main)added:docs/src/options/callback/tutorial004.py+18 added
1+import typer2+3+4+def 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 value11+12+13+def main(name: str = typer.Option(..., callback=name_callback)):14+ typer.echo(f"Hello {name}")15+16+17+if __name__ == "__main__":18+ typer.run(main)added:docs/src/options/password/tutorial001.py+11 added
1+import typer2+3+4+def main(5+ name: str, email: str = typer.Option(..., prompt=True, confirmation_prompt=True)6+):7+ typer.echo(f"Hello {name}, your email is {email}")8+9+10+if __name__ == "__main__":11+ typer.run(main)added:docs/src/options/password/tutorial002.py+15 added
1+import typer2+3+4+def 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}")12+13+14+if __name__ == "__main__":15+ typer.run(main)modified:docs/src/options/prompt/tutorial002.py+1 added-2 removed
1 import typer2 3 4 def 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}")8 9 2 unmodified linesadded:docs/src/options/version/tutorial001.py+20 added
1+import typer2+3+__version__ = "0.1.0"4+5+6+def version_callback(value: bool):7+ if value:8+ typer.echo(f"Awesome CLI Version: {__version__}")9+ raise typer.Exit()10+11+12+def main(13+ name: str = typer.Option("World"),14+ version: bool = typer.Option(None, "--version", callback=version_callback),15+):16+ typer.echo(f"Hello {name}")17+18+19+if __name__ == "__main__":20+ typer.run(main)added:docs/src/options/version/tutorial002.py+25 added
1+import typer2+3+__version__ = "0.1.0"4+5+6+def version_callback(value: bool):7+ if value:8+ typer.echo(f"Awesome CLI Version: {__version__}")9+ raise typer.Exit()10+11+12+def name_callback(name: str):13+ if name != "Camila":14+ raise typer.BadParameter("Only Camila is allowed")15+16+17+def 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}")22+23+24+if __name__ == "__main__":25+ typer.run(main)added:docs/src/options/version/tutorial003.py+28 added
1+import typer2+3+__version__ = "0.1.0"4+5+6+def version_callback(value: bool):7+ if value:8+ typer.echo(f"Awesome CLI Version: {__version__}")9+ raise typer.Exit()10+11+12+def name_callback(name: str):13+ if name != "Camila":14+ raise typer.BadParameter("Only Camila is allowed")15+ return name16+17+18+def 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}")25+26+27+if __name__ == "__main__":28+ typer.run(main)modified:docs/src/parameter_types/index/tutorial001.py+1 added-3 removed
1 import typer2 3 4-def main(5- name: str, age: int = 20, height_meters: float = 1.89, female: bool = True,6-):4+def 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 linesadded:docs/src/printing/tutorial003.py+9 added
1+import typer2+3+4+def main():5+ typer.echo(f"Here is something written to standard error", err=True)6+7+8+if __name__ == "__main__":9+ typer.run(main)added:docs/src/testing/app01/__init__.py
added:docs/src/testing/app01/main.py+14 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command()7+def 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}")11+12+13+if __name__ == "__main__":14+ app()added:docs/src/testing/app01/test_main.py+12 added
1+from typer.testing import CliRunner2+3+from .main import app4+5+runner = CliRunner()6+7+8+def 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.stdoutadded:docs/src/testing/app02/__init__.py
added:docs/src/testing/app02/main.py+12 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command()7+def main(name: str, email: str = typer.Option(..., prompt=True)):8+ typer.echo(f"Hello {name}, your email is: {email}")9+10+11+if __name__ == "__main__":12+ app()added:docs/src/testing/app02/test_main.py+11 added
1+from typer.testing import CliRunner2+3+from .main import app4+5+runner = CliRunner()6+7+8+def 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.stdoutadded:docs/src/testing/app03/__init__.py
added:docs/src/testing/app03/main.py+9 added
1+import typer2+3+4+def main(name: str = "World"):5+ typer.echo(f"Hello {name}")6+7+8+if __name__ == "__main__":9+ typer.run(main)added:docs/src/testing/app03/test_main.py+15 added
1+import typer2+from typer.testing import CliRunner3+4+from .main import main5+6+app = typer.Typer()7+app.command()(main)8+9+runner = CliRunner()10+11+12+def test_app():13+ result = runner.invoke(app, ["--name", "Camila"])14+ assert result.exit_code == 015+ assert "Hello Camila" in result.stdoutmodified:docs/tutorial/commands/callback.md+21 added
160 unmodified lines161 Creating user: Camila162 ```163 164 </div>165+166+## Click Group167+168+If 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>.169+170+For example:171+172+```Python173+import click174+175+@click.group()176+def cli():177+ pass178+```179+180+The original function `cli` would be the equivalent of a Typer callback.181+182+!!! 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.184+185+ **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
1+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.2+3+But you can access the context by declaring a function parameter of type `typer.Context`.4+5+You might have read it in [CLI Option Callback and Context](../options/callback-and-context.md){.internal-link target=_blank}.6+7+The same way, in commands or in the main `Typer` callback you can access the context by declaring a function parameter of type `typer.Context`.8+9+## Getting the context10+11+For example, let's say that you want to execute some logic in a `Typer` callback depending on the subcommand that is being called.12+13+You can get the name of the subcommand from the context:14+15+```Python hl_lines="17 21"16+{!./src/commands/context/tutorial001.py!}17+```18+19+Check it:20+21+<div class="termy">22+23+```console24+$ python main.py create Camila25+26+// We get the message from the callback27+About to execute command: create28+Creating user: Camila29+30+$ python main.py delete Camila31+32+// We get the message from the callback, this time with delete33+About to execute command: delete34+Deleting user: Camila35+```36+37+</div>38+39+## Executable callback40+41+By default, the callback is only executed right before executing a command.42+43+And if no command is provided, the help message is shown.44+45+But we could make it run even without a subcommand with `invoke_without_command=True`:46+47+```Python hl_lines="16"48+{!./src/commands/context/tutorial002.py!}49+```50+51+Check it:52+53+<div class="termy">54+55+```console56+$ python main.py57+58+// The callback is executed, we don't get the default help message59+Initializing database60+61+// Try with a command62+$ python main.py create Camila63+64+// The callback is still executed65+Initializing database66+Creating user: Camila67+```68+69+</div>70+71+## Exclusive executable callback72+73+We might not want the callback to be executed if there's already other command that will be executed.74+75+For that, we can get the `typer.Context` and check if there's an invoked command in `ctx.invoked_subcommand`.76+77+If it's `None`, it means that we are not calling a subcommand but the main program (the callback) directly:78+79+```Python hl_lines="17 21"80+{!./src/commands/context/tutorial003.py!}81+```82+83+Check it:84+85+<div class="termy">86+87+```console88+$ python main.py89+90+// The callback is executed91+Initializing database92+93+// Check it with a subcommand94+$ python main.py create Camila95+96+// This time the callback is not executed97+Creating user: Camila98+```99+100+</div>101+102+## Configuring the context103+104+You can pass configurations for the context when creating a command or callback.105+106+To 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>.107+108+For example, you could keep additional *CLI parameters* not declared in your CLI program with `ignore_unknown_options` and `allow_extra_args`.109+110+Then you can access those extra raw *CLI parameters* as a `list` of `str` in `ctx.args`:111+112+```Python hl_lines="7 9 10"113+{!./src/commands/context/tutorial004.py!}114+```115+116+<div class="termy">117+118+```console119+$ python main.py --name Camila --city Berlin120+121+Got extra arg: --name122+Got extra arg: Camila123+Got extra arg: --city124+Got extra arg: Berlin125+```126+127+</div>128+129+!!! 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
1-We have seen how to create a CLI program with possibly several *CLI Options* and *CLI Arguments*.1+We have seen how to create a CLI program with possibly several *CLI options* and *CLI arguments*.2 3 But **Typer** allows you to create CLI programs with several commands (also known as subcommands).4 5 For example, the program `git` has several commands.22 unmodified lines28 29 It's like if the same big program `git` had several small programs inside.30 31 !!! 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.33 34 ## Command or subcommand35 36 It's common to call a CLI program a "command".7 unmodified lines44 ## Explicit application45 46 Before creating CLI applications with multiple commands/subcommands we need to understand how to create an explicit `typer.Typer()` application.47 48-In the *CLI Options* and *CLI Argument* tutorials you have seen how to create a single function and then pass that function to `typer.run()`.48+In the *CLI options* and *CLI argument* tutorials you have seen how to create a single function and then pass that function to `typer.run()`.49 50 For example:51 52 ```Python hl_lines="9"114 unmodified lines167 168 !!! tip169 By default, the names of the commands are generated from the function name.170 171+## Click Group172+173+If 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>.174+175+!!! 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.177+178+ 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.179+180 ## Decorator Technical Details181 182 When 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 linesadded:docs/tutorial/options/autocompletion.md+363 added
1+As you have seen, apps built with **Typer** have completion in your shell that works when you create a Python package or using **Typer CLI**.2+3+It normally completes *CLI options*, *CLI arguments*, and subcommands (that you will learn about later).4+5+But you can also provide auto completion for the **values** of *CLI options* and *CLI arguments*. We will learn about that here.6+7+## Review completion8+9+Before checking how to provide custom completions, let's check again how it works.10+11+After 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).12+13+To check it quickly without creating a new Python package, install [Typer CLI](../../typer-cli.md){.internal-link target=_blank}.14+15+Then let's create small example script:16+17+```Python18+{!./src/options/autocompletion/tutorial001.py!}19+```20+21+And let's try it with **Typer CLI** to get completion:22+23+<div class="termy">24+25+```console26+// Hit the TAB key in your keyboard below where you see the: [TAB]27+$ typer ./main.py [TAB][TAB]28+29+// Depending on your terminal/shell you will get some completion like this ✨30+run -- Run the provided Typer app.31+utils -- Extra utility commands for Typer apps.32+33+// Then try with "run" and --34+$ typer ./main.py run --[TAB][TAB]35+36+// You will get completion for --name, depending on your terminal it will look something like this37+--name -- The name to say hi to.38+39+// And you can run it as if it was with Python directly40+$ typer ./main.py run --name Camila41+42+Hello Camila43+```44+45+</div>46+47+## Custom completion for values48+49+Right now we get completion for the *CLI option* names, but not for the values.50+51+We 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}:52+53+```Python hl_lines="4 5 10"54+{!./src/options/autocompletion/tutorial002.py!}55+```56+57+We return a `list` of strings from the `complete_name()` function.58+59+And then we get those values when using completion:60+61+<div class="termy">62+63+```console64+$ typer ./main.py run --name [TAB][TAB]65+66+// We get the values returned from the function 🎉67+Camila Carlos Sebastian68+```69+70+</div>71+72+We got the basics working. Now let's improve it.73+74+## Check the incomplete value75+76+Right 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`.77+78+But we can fix that so that it always works correctly.79+80+Modify the `complete_name()` function to receive a parameter of type `str`, it will contain the incomplete value.81+82+Then we can check and return only the values that start with the incomplete value from the command line:83+84+```Python hl_lines="6 7 8 9 10 11"85+{!./src/options/autocompletion/tutorial003.py!}86+```87+88+Now let's try it:89+90+<div class="termy">91+92+```console93+$ typer ./main.py run --name Ca[TAB][TAB]94+95+// We get the values returned from the function that start with Ca 🎉96+Camila Carlos97+```98+99+</div>100+101+Now we are only returning the valid values, that start with `Ca`, we are no longer returning `Sebastian` as a completion option.102+103+!!! tip104+ You have to declare the incomplete value of type `str` and that's what you will receive in the function.105+106+ 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.107+108+ And the same way, you can only return `str`, not `int`, etc.109+110+## Add help to completions111+112+Right now we are returning a `list` of `str`.113+114+But some shells (Zsh, Fish, PowerShell) are capable of showing extra help text for completion.115+116+We can provide that extra help text so that those shells can show it.117+118+In 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.119+120+So, in the end, we return a `list` of `tuples` of `str`:121+122+```Python hl_lines="3 4 5 6 7 10 11 12 13 14 15 16"123+{!./src/options/autocompletion/tutorial004.py!}124+```125+126+!!! tip127+ If you want to have help text for each item, make sure each item in the list is a `tuple`. Not a `list`.128+129+ Click checks specifically for a `tuple` when extracting the help text.130+131+ So in the end, the return will be a `list` (or other iterable) of `tuples` of 2 `str`.132+133+!!! info134+ The help text will be visible in Zsh, Fish, and PowerShell.135+136+ Bash doesn't support showing the help text, but completion will still work the same.137+138+If you have a shell like Zsh, it would look like:139+140+<div class="termy">141+142+```console143+$ typer ./main.py run --name [TAB][TAB]144+145+// We get the completion items with their help text 🎉146+Camila -- The reader of books.147+Carlos -- The writer of scripts.148+Sebastian -- The type hints guy.149+```150+151+</div>152+153+## Simplify with `yield`154+155+Instead of creating and returning a list with values (`str` or `tuple`), we can use `yield` with each value that we want in the completion.156+157+That 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:158+159+```Python hl_lines="10 11 12 13"160+{!./src/options/autocompletion/tutorial005.py!}161+```162+163+That simplifies our code a bit and works the same.164+165+!!! tip166+ If all the `yield` part seems complex for you, don't worry, you can just use the version with the `list` above.167+168+ In the end, that's just to save us a couple of lines of code.169+170+!!! 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>.172+173+ But each of the elements for completion has to be a `str` or a `tuple` (when containing a help text).174+175+## Access other *CLI parameters* with the Context176+177+Let's say that now we want to modify the program to be able to "say hi" to multiple people at the same time.178+179+So, we will allow multiple `--name` *CLI options*.180+181+!!! tip182+ You will learn more about *CLI parameters* with multiple values later in the tutorial.183+184+ So, for now, take this as a sneak peek 😉.185+186+For this we use a `List` of `str`:187+188+```Python hl_lines="6 7 8"189+{!./src/options/autocompletion/tutorial006.py!}190+```191+192+And then we can use it like:193+194+<div class="termy">195+196+```console197+$ typer ./main.py run --name Camila --name Sebastian198+199+Hello Camila200+Hello Sebastian201+```202+203+</div>204+205+### Getting completion for multiple values206+207+And 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.208+209+For 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.210+211+But you can access the context by declaring a function parameter of type `typer.Context`.212+213+And from that context you can get the current values for each parameter.214+215+```Python hl_lines="12 13 15"216+{!./src/options/autocompletion/tutorial007.py!}217+```218+219+We are getting the `names` already provided with `--name` in the command line before this completion was triggered.220+221+If 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.222+223+Then, 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`.224+225+And then we `yield` each item that has not being used yet.226+227+Check it:228+229+<div class="termy">230+231+```console232+$ typer ./main.py run --name [TAB][TAB]233+234+// The first time we trigger completion, we get all the names235+Camila -- The reader of books.236+Carlos -- The writer of scripts.237+Sebastian -- The type hints guy.238+239+// Add a name and trigger completion again240+$ typer ./main.py run --name Sebastian --name Ca[TAB][TAB]241+242+// Now we get completion only for the names we haven't used 🎉243+Camila -- The reader of books.244+Carlos -- The writer of scripts.245+246+// And if we add another of the available names:247+$ typer ./main.py run --name Sebastian --name Camila --name [TAB][TAB]248+249+// We get completion for the only available one250+Carlos -- The writer of scripts.251+```252+253+</div>254+255+!!! 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.257+258+## Getting the raw *CLI parameters*259+260+You can also get the raw *CLI parameters*, just a `list` of `str` with everything passed in the command line before the incomplete value.261+262+For example, something like `["typer", "main.py", "run", "--name"]`.263+264+!!! tip265+ This would be for advanced scenarios, in most use cases you would be better of using the context.266+267+ But it's still possible if you need it.268+269+As a simple example, let's show it on the screen before completion.270+271+Because 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.272+273+### Printing to "standard error"274+275+!!! 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}.277+278+The completion system only reads from "standard output", so, printing to "standard error" won't break completion. 🚀279+280+You can print to "standard error" with `typer.echo("some text", err=True)`.281+282+Using `err=True` tells **Typer** (actually Click) that the output should be shown in "standard error".283+284+```Python hl_lines="12 13"285+{!./src/options/autocompletion/tutorial008.py!}286+```287+288+We get all the *CLI parameters* as a raw `list` of `str` by declaring a parameter with type `List[str]`, here it's named `args`.289+290+!!! tip291+ Here we name the list of all the raw *CLI parameters* `args` because that's the convention with Click.292+293+ But it doesn't contain only *CLI arguments*, it has everything, including *CLI options* and values, as a raw `list` of `str`.294+295+And then we just print it to "standard error".296+297+<div class="termy">298+299+```console300+$ typer ./main.py run --name [TAB][TAB]301+302+// First we see the raw CLI parameters303+['./main.py', 'run', '--name']304+305+// And then we see the actual completion306+Camila -- The reader of books.307+Carlos -- The writer of scripts.308+Sebastian -- The type hints guy.309+```310+311+</div>312+313+!!! tip314+ This is a very simple (and quite useless) example, just so you know how it works and that you can use it.315+316+ But it's probably useful only in very advanced use cases.317+318+## Getting the Context and the raw *CLI parameters*319+320+Of course, you can declare everything if you need it, the context, the raw *CLI parameters*, and the incomplete `str`:321+322+```Python hl_lines="12"323+{!./src/options/autocompletion/tutorial009.py!}324+```325+326+Check it:327+328+<div class="termy">329+330+```console331+$ typer ./main.py run --name [TAB][TAB]332+333+// First we see the raw CLI parameters334+['./main.py', 'run', '--name']335+336+// And then we see the actual completion337+Camila -- The reader of books.338+Carlos -- The writer of scripts.339+Sebastian -- The type hints guy.340+341+$ typer ./main.py run --name Sebastian --name Ca[TAB][TAB]342+343+// Again, we see the raw CLI parameters344+['./main.py', 'run', '--name', 'Sebastian', '--name']345+346+// And then we see the rest of the valid completion items347+Camila -- The reader of books.348+Carlos -- The writer of scripts.349+```350+351+</div>352+353+## Types, types everywhere354+355+**Typer** uses the type declarations to detect what it has to provide to your `autocompletion` function.356+357+You can declare function parameters of these types:358+359+* `str`: for the incomplete value.360+* `typer.Context`: for the current context.361+* `List[str]`: for the raw *CLI parameters*.362+363+It 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
1+In 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.2+3+In those cases you can use a *CLI parameter* callback function.4+5+## Validate *CLI parameters*6+7+For example, you could do some validation before the rest of the code is executed.8+9+```Python hl_lines="4 5 6 7 10"10+{!./src/options/callback/tutorial001.py!}11+```12+13+Here you pass a function to `typer.Option()` or `typer.Argument()` with the keyword argument `callback`.14+15+The function receives the value from the command line. It can do anything with it, and then return the value.16+17+In this case, if the `--name` is not `Camila` we raise a `typer.BadParameter()` exception.18+19+The `BadParameter` exception is special, it shows the error with the parameter that generated it.20+21+Check it:22+23+<div class="termy">24+25+```console26+$ python main.py --name Camila27+28+Hello Camila29+30+$ python main.py --name Rick31+32+Usage: main.py [OPTIONS]33+34+// We get the error from the callback35+Error: Invalid value for '--name': Only Camila is allowed36+```37+38+</div>39+40+## Handling completion41+42+There's something to be aware of with callbacks and completion that requires some small special handling.43+44+But first let's just use completion in your shell (Bash, Zsh, Fish, or PowerShell).45+46+After 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).47+48+To 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:49+50+<div class="termy">51+52+```console53+// Hit the TAB key in your keyboard below where you see the: [TAB]54+$ typer ./main.py [TAB][TAB]55+56+// Depending on your terminal/shell you will get some completion like this ✨57+run -- Run the provided Typer app.58+utils -- Extra utility commands for Typer apps.59+60+// Then try with "run" and --help61+$ typer ./main.py run --help62+63+// You get a help text with your CLI options as you normally would64+Usage: typer run [OPTIONS]65+66+ Run the provided Typer app.67+68+Options:69+ --name TEXT [required]70+ --help Show this message and exit.71+72+// Then try completion with your program73+$ typer ./main.py run --[TAB][TAB]74+75+// You get completion for CLI options76+--help -- Show this message and exit.77+--name78+79+// And you can run it as if it was with Python directly80+$ typer ./main.py run --name Camila81+82+Hello Camila83+```84+85+</div>86+87+### How shell completion works88+89+The 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.90+91+But the main **important point** is that it is all based on values printed by your program that the shell reads.92+93+### Breaking completion in a callback94+95+Let's say that when the callback is running, we want to show a message saying that it's validating the name:96+97+```Python hl_lines="5"98+{!./src/options/callback/tutorial002.py!}99+```100+101+And 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.102+103+It will look something like:104+105+<div class="termy">106+107+```console108+// Run it normally109+$ typer ./main.py run --name Camila110+111+// See the extra message "Validating name"112+Validating name113+Hello Camila114+115+$ typer ./main.py run --[TAB][TAB]116+117+// Some weird broken error message ⛔️118+(eval):1: command not found: Validating119+rutyper ./main.pyed Typer app.120+```121+122+</div>123+124+### Fix completion - using the `Context`125+126+When you create a **Typer** application it uses Click underneath.127+128+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.129+130+But you can access the context by declaring a function parameter of type `typer.Context`.131+132+The "context" has some additional data about the current execution of your program:133+134+```Python hl_lines="4 5 6"135+{!./src/options/callback/tutorial003.py!}136+```137+138+The `ctx.resilient_parsing` will be `True` when handling completion, so you can just return without printing anything else.139+140+But it will be `False` when calling the program normally. So you can continue the execution of your previous code.141+142+That's all is needed to fix completion 🚀143+144+Check it:145+146+<div class="termy">147+148+```console149+$ typer ./main.py run --[TAB][TAB]150+151+// Now it works correctly 🎉152+--help -- Show this message and exit.153+--name154+155+// And you can call it normally156+$ typer ./main.py run --name Camila157+158+Validating name159+Hello Camila160+```161+162+</div>163+164+## Using the `CallbackParam` object165+166+The 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.167+168+```Python hl_lines="4 7"169+{!./src/options/callback/tutorial004.py!}170+```171+172+It's probably not very common, but you could do it if you need it.173+174+For 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.175+176+Check it:177+178+<div class="termy">179+180+```console181+$ python main.py --name Camila182+183+Validating param: name184+Hello Camila185+```186+187+</div>188+189+## Technical Details190+191+Because 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.192+193+And **Typer** will make sure you get the function parameters you want.194+195+You don't have to worry about their names, their order, etc.196+197+As it's based on standard Python types, it "**just works**". ✨198+199+### Click's `Parameter`200+201+The `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.202+203+### Callback with type annotations204+205+You can get the `typer.Context` and the `typer.CallbackParam` simply by declaring a function parameter of each type.206+207+The order doesn't matter, the name of the function parameters doesn't matter.208+209+You could also get only the `typer.CallbackParam` and not the `typer.Context`, or vice versa, it will still work.210+211+### `value` function parameter212+213+The `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.214+215+It's also possible to not declare its type. It will still work.216+217+And 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
1+Apart from having a prompt, you can make a *CLI option* have a `confirmation_prompt=True`:2+3+```Python hl_lines="5"4+{!./src/options/password/tutorial001.py!}5+```6+7+And the CLI program will ask for confirmation:8+9+<div class="termy">10+11+```console12+$ python main.py Camila13+14+// It prompts for the email15+# Email: $ camila@example.com16+# Repeat for confirmation: $ camila@example.com17+18+Hello Camila, your email is camila@example.com19+```20+21+</div>22+23+## A Password prompt24+25+When receiving a password, it is very common (in most shells) to not show anything on the screen while typing the password.26+27+The program will still receive the password, but nothing will be shown on screen, not even `****`.28+29+You can achieve the same using `hide_input=True`.30+31+And if you combine it with `confirmation_prompt=True` you can easily receive a password with double confirmation:32+33+```Python hl_lines="6 7 8"34+{!./src/options/password/tutorial002.py!}35+```36+37+Check it:38+39+<div class="termy">40+41+```console42+$ python main.py Camila43+44+// It prompts for the password, but doesn't show anything when you type45+# Password: $ 46+# Repeat for confirmation: $ 47+48+// Let's imagine the password typed was "typerrocks"49+Hello Camila. Doing something very secure with password.50+...just kidding, here it is, very insecure: typerrocks51+```52+53+</div>modified:docs/tutorial/options/prompt.md+1 added-1 removed
22 unmodified lines23 ## Customize the prompt24 25 You can also set a custom prompt, passing the string that you want to use instead of just `True`:26 27-```Python hl_lines="6"27+```Python hl_lines="5"28 {!./src/options/prompt/tutorial002.py!}29 ```30 31 And then your program will ask for it using with your custom prompt:57 unmodified linesadded:docs/tutorial/options/version.md+107 added
1+You could use a callback to implement a `--version` *CLI option*.2+3+It would show the version of your CLI program and then it would terminate it. Even before any other *CLI parameter* is processed.4+5+## First version of `--version`6+7+Let's see a first version of how it could look like:8+9+```Python hl_lines="6 7 8 9 14"10+{!./src/options/version/tutorial001.py!}11+```12+13+!!! 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.15+16+If the `--version` *CLI option* is passed, we get a value `True` in the callback.17+18+Then we can print the version and raise `typer.Exit()` to make sure the program is terminated before anything else is executed.19+20+We also declare the explicit *CLI option* name `--version`, because we don't want an automatic `--no-version`, it would look awkward.21+22+Check it:23+24+<div class="termy">25+26+```console27+$ python main.py --help28+29+// We get a --version, and don't get an awkward --no-version 🎉30+Usage: main.py [OPTIONS]31+32+Options: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.37+38+ --help Show this message and exit.39+40+41+// We can call it normally42+$ python main.py --name Camila43+44+Hello Camila45+46+// And we can get the version47+$ python main.py --version48+49+Awesome CLI Version: 0.1.050+51+// Because we exit in the callback, we don't get a "Hello World" message after the version 🚀52+```53+54+</div>55+56+## Previous parameters and `is_eager`57+58+But 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:59+60+```Python hl_lines="12 13 14 18"61+{!./src/options/version/tutorial002.py!}62+```63+64+Then 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:65+66+<div class="termy">67+68+```console69+$ python main.py --name Rick --version70+71+Only Camila is allowed72+Aborted!73+```74+75+</div>76+77+!!! 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`.79+80+!!! 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.82+83+!!! 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}.85+86+### Fix with `is_eager`87+88+For those cases, we can mark a *CLI parameter* (a *CLI option* or *CLI argument*) with `is_eager=True`.89+90+That will tell **Typer** (actually Click) that it should process this *CLI parameter* before the others:91+92+```Python hl_lines="21"93+{!./src/options/version/tutorial003.py!}94+```95+96+Check it:97+98+<div class="termy">99+100+```console101+$ python main.py --name Rick --version102+103+// Now we only get the version, and the name is not used104+Awesome CLI Version: 0.1.0105+```106+107+</div>modified:docs/tutorial/parameter-types/index.md+1 added-1 removed
4 unmodified lines5 When you declare a *CLI parameter* with some type **Typer** will convert the data received in the command line to that data type.6 7 For example:8 9-```Python hl_lines="5"9+```Python hl_lines="4"10 {!./src/parameter_types/index/tutorial001.py!}11 ```12 13 In this example, the value received for the *CLI argument* `NAME` will be treated as `str`.52 unmodified linesmodified:docs/tutorial/arguments.md+1 added-1 removed
45 unmodified lines46 ```Python hl_lines="4"47 {!./src/arguments/tutorial001.py!}48 ```49 50-Before you had this function parameter:50+Before, you had this function parameter:51 52 ```Python53 name: str54 ```154 unmodified linesmodified:docs/tutorial/first-steps.md+5 added-5 removed
1 ## The simplest example2 3-The simplest Typer file could look like this:3+The simplest **Typer** file could look like this:4 5 ```Python6 {!./src/first_steps/tutorial001.py!}7 ```164 unmodified lines172 The program knows it has to show the size because it sees `--size`, not because of the order.173 174 A *CLI option* like `--size` doesn't depend on the order like a *CLI argument*.175 176-So, if you put the `--size` *before* the *CLI argument*, it still works:176+So, if you put the `--size` *before* the *CLI argument*, it still works (in fact, that's the most common way of doing it):177 178 <div class="termy">179 180 ```console237 unmodified lines418 And a parameter like `name`, that doesn't have a default value, is considered *required*.419 420 ### In CLIs421 422-When 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.422+When 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.423 424 But 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`.425 426 The 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 lines430 ### In **Typer**431 432 To try and make it a bit easier, we'll normally use the words "parameter" or "argument" to refer to Python functions.433 434-We'll use ***CLI argument*** to refer to those *CLI parameters* that depend on an order. That are **required** by default.434+We'll use ***CLI argument*** to refer to those *CLI parameters* that depend on the specific order. That are **required** by default.435 436 And 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.437 438 We will use ***CLI parameter*** to refer to both, *CLI arguments* and *CLI options*.29 unmodified lines468 </div>469 470 ...and it will give you auto completion in your terminal when you hit <kbd>TAB</kbd> for all your code.471 472-So you can use it to have auto completion as you continue with the tutorial.472+So you can use it to have auto completion for your own scripts as you continue with the tutorial.473 474 !!! 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 linemodified:docs/tutorial/index.md+5 added-5 removed
9 unmodified lines10 def type_example(name: str, formal: bool = False, intro: str = None):11 pass12 ```13 14-And your editor (and Typer) will know that:14+And your editor (and **Typer**) will know that:15 16 * `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.19 20 These type hints are what give you autocomplete in your editor and several other features.21 22-Typer is based on these type hints.22+**Typer** is based on these type hints.23 24 ## Intro25 26 This tutorial shows you how to use **Typer** with all its features, step by step.21 unmodified lines48 </div>49 50 It is **HIGHLY encouraged** that you write or copy the code, edit it and run it locally.51 52-Using 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.52+Using 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.53 54 And running the examples is what will really help you understand what is going on.55 56 You can learn a lot more by running some examples and playing around with them than by reading all the docs here.10 unmodified lines67 68 ```console69 $ pip install typer[all]70 ---> 100%71-Successfully installed typer click colorama click-completion71+Successfully installed typer click colorama shellingham72 ```73 74 </div>75 76-...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 lines39 {!./src/printing/tutorial001.py!}40 ```41 42 !!! 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"`.44 45 But **Typer** provides them all as variables like `typer.colors.GREEN` just so you can use autocompletion while selecting them.46 47 Check it:32 unmodified lines80 <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>84+85+## "Standard Output" and "Standard Error"86+87+The 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**".88+89+When our code "prints" things it is actually "writing" to this "virtual file" of "standard output".90+91+This might seem strange, but that's how the CLI program and the operating system interact with each other.92+93+And then the operating system **shows on the screen** whatever our CLI program "**wrote**" to that "**virtual file**" called "**standard output**".94+95+### Standard Error96+97+And there's another "**virtual file**" called "**standard error**" that is normally only used for errors.98+99+But we can also "print" to "standard error". And both are shown on the terminal to the users.100+101+!!! info102+ If you use PowerShell it's quite possible that what you print to "standard error" won't be shown in the terminal.103+104+ In PowerShell, to see "standard error" you would have to check the variable `$Error`.105+106+ But it will work normally in Bash, Zsh, and Fish.107+108+### Printing to "standard error"109+110+You can print to "standard error" with `typer.echo("some text", err=True)`.111+112+Using `err=True` tells **Typer** (actually Click) that the output should be shown in "standard error".113+114+```Python hl_lines="5"115+{!./src/printing/tutorial003.py!}116+```117+118+When you try it in the terminal, it will probably just look the same:119+120+<div class="termy">121+122+```console123+$ python main.py124+125+Here is something written to standard error126+```127+128+</div>129+130+### "Standard Input"131+132+As 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.133+134+This virtual file is called "**standard input**".135+136+### What is this for137+138+Right now this probably seems quite useless 🤷♂.139+140+But 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 lines86 87 </div>88 89 !!! 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.91 92 ## Abort93 94 There's a special exception that you can use to "abort" a program.24 unmodified linesadded:docs/tutorial/testing.md+213 added
1+Testing **Typer** applications is very easy with <a href="https://docs.pytest.org/en/latest/" class="external-link" target="_blank">pytest</a>.2+3+Let's say you have an application `app/main.py` with:4+5+```Python6+{!./src/testing/app01/main.py!}7+```8+9+So, you would use it like:10+11+<div class="termy">12+13+```console14+$ python main.py Camila --city Berlin15+16+Hello Camila17+Let's have a coffee in Berlin18+```19+20+</div>21+22+And the directory also has an empty `app/__init__.py` file.23+24+So, the `app` is a "Python package".25+26+## Test the app27+28+### Import and create a `CliRunner`29+30+Create another file/module `app/test_main.py`.31+32+Import `CliRunner` and create a `runner` object.33+34+This runner is what will "invoke" or "call" your command line application.35+36+```Python hl_lines="1 5"37+{!./src/testing/app01/test_main.py!}38+```39+40+!!! 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.42+43+### Call the app44+45+Then create a function `test_app()`.46+47+And inside of the function, use the `runner` to `invoke` the application.48+49+The first parameter to `runner.invoke()` is a `Typer` app.50+51+The second parameter is a `list` of `str`, with all the text you would pass in the command line, right as you would pass it:52+53+```Python hl_lines="8 9"54+{!./src/testing/app01/test_main.py!}55+```56+57+!!! tip58+ The name of the function has to start with `test_`, that way pytest can detect it and use it automatically.59+60+### Check the result61+62+Then, inside of the test function, add `assert` statements to ensure that everything in the result of the call is as it should be.63+64+```Python hl_lines="10 11 12"65+{!./src/testing/app01/test_main.py!}66+```67+68+Here we are checking that the exit code is 0, as it is for programs that exit without errors.69+70+Then we check that the text printed to "standard output" contains the text that our CLI program prints.71+72+!!! tip73+ You could also check `result.stderr` for "standard error".74+75+!!! 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}.77+78+### Call `pytest`79+80+Then you can call `pytest` in your directory and it will run your tests:81+82+<div class="termy">83+84+```console85+$ pytest86+87+================ test session starts ================88+platform linux -- Python 3.6.9, pytest-5.3.5, py-1.8.1, pluggy-0.13.189+rootdir: /home/user/code/superawesome-cli/app90+plugins: forked-1.1.3, xdist-1.31.0, cov-2.8.191+collected 1 item92+93+---> 100%94+95+test_main.py <span style="color: green;">. [100%]</span>96+97+<span style="color: green;">================= 1 passed in 0.03s =================</span>98+```99+100+</div>101+102+## Testing input103+104+If you have a CLI with prompts, like:105+106+```Python hl_lines="7"107+{!./src/testing/app02/main.py!}108+```109+110+That you would use like:111+112+<div class="termy">113+114+```console115+$ python main.py Camila116+117+# Email: $ camila@example.com118+119+Hello Camila, your email is: camila@example.com120+```121+122+</div>123+124+You can test the input typed in the terminal using `input="camila@example.com\n"`.125+126+This 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".127+128+!!! 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}.130+131+When 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"`.132+133+So, if you use `input="camila@example.com\n"` it means: "type `camila@example.com` in the terminal, then hit the <kbd>ENTER</kbd> key":134+135+```Python hl_lines="9"136+{!./src/testing/app02/test_main.py!}137+```138+139+## Test a function140+141+If you have a script and you never created an explicit `typer.Typer` app, like:142+143+```Python hl_lines="9"144+{!./src/testing/app03/main.py!}145+```146+147+...you can still test it, by creating an app during testing:148+149+```Python hl_lines="6 7 13"150+{!./src/testing/app03/test_main.py!}151+```152+153+Of 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.154+155+But if you want to keep it that way, e.g. because it's a simple example in documentation, then you can use that trick.156+157+### About the `app.command` decorator158+159+Notice the `app.command()(main)`.160+161+If it's not obvious what it's doing, continue reading...162+163+You would normally write something like:164+165+```Python166+@app.command()167+def main(name: str = "World"):168+ # Some code here169+```170+171+But `@app.command()` is just a decorator.172+173+That's equivalent to:174+175+```Python176+def main(name: str = "World"):177+ # Some code here178+179+decorator = app.command()180+181+new_main = decorator(main)182+main = new_main183+```184+185+`app.command()` returns a function (`decorator`) that takes another function as it's only parameter (`main`).186+187+And 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`).188+189+Now, in the specific case of **Typer**, the decorator doesn't change the original function. It registers it internally and returns it unmodified.190+191+So, `new_main` is actually the same original `main`.192+193+So, in the case of **Typer**, as it doesn't really modify the decorated function, that would be equivalent to:194+195+```Python196+def main(name: str = "World"):197+ # Some code here198+199+decorator = app.command()200+201+decorator(main)202+```203+204+But then we don't need to create the variable `decorator` to use it below, we can just use it directly:205+206+```Python207+def main(name: str = "World"):208+ # Some code here209+210+app.command()(main)211+```212+213+...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 lines23 24 It inspired a lot of the ideas in **FastAPI** and **Typer**.25 26 !!! 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.28 29 ### <a href="https://micheles.github.io/plac/" class="external-link" target="_blank">Plac</a>30 31 Plac is another library to create CLIs using parameters in functions, similar to Hug.17 unmodified lines49 Click is one of the most widely used libraries to create CLIs in Python.50 51 It's a very powerful tool and there are many CLIs built with it. It is what powers **Typer** underneath.52 53-It 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).53+It 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).54 55 It 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.56 57 It was built with some great ideas and design using the features available in the language at the time (Python 2.x).26 unmodified linesmodified:docs/features.md+5 added-3 removed
1 ## Design based on **FastAPI**2 3+<a href="https://fastapi.tiangolo.com" target="_blank"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" style="width: 20%;"></a>4+5 **Typer** is <a href="https://fastapi.tiangolo.com" class="external-link" target="_blank">FastAPI</a>'s little sibling.6 5-It follows the same design and ideas. If you know FastAPI, you already know **Typer**... more or less.7+It follows the same design and ideas. If you know **FastAPI**, you already know **Typer**... more or less.8 9 ## Just Modern Python10 11 It's all based on standard **Python 3.6 type** declarations. No new syntax to learn. Just standard modern Python.45 unmodified lines57 58 * `--install-completion`: Install completion for the current shell.59 * `--show-completion`: Show completion for the current shell, to copy it or customize the installation.60 59- 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`.65 66 Then you can tell the user to install completion after installing your CLI program and the rest will just work.67 68 !!! 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.70 71 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.72 73 ## The power of Click16 unmodified linesmodified:docs/index.md+13 added-7 removed
22 unmodified lines23 **Source Code**: <a href="https://github.com/tiangolo/typer" target="_blank">https://github.com/tiangolo/typer</a>24 25 ---26 27-Typer 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.27+Typer 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.28 29-**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.30-29 The key features are:30 31 * **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.36 37+## FastAPI of CLIs38+39+<a href="https://fastapi.tiangolo.com" target="_blank"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" style="width: 20%;"></a>40+41+**Typer** is <a href="https://fastapi.tiangolo.com" class="external-link" target="_blank">FastAPI</a>'s little sibling.42+43+And it's intended to be the FastAPI of CLIs.44+45 ## Requirements46 47 Python 3.6+48 43-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>.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>.50 51 ## Installation52 53 <div class="termy">170 unmodified lines224 </div>225 226 ### Recap227 222-In summary, you declare **once** the types of parameters (*arguments* and *options*) as function parameters.228+In summary, you declare **once** the types of parameters (*CLI arguments* and *CLI options*) as function parameters.229 230 You do that with standard modern Python types.231 232 You don't have to learn a new syntax, the methods or classes of a specific library, etc.30 unmodified lines263 * 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`.268 269 You can install `typer` with `colorama` and `shellingham` with `pip install typer[all]`.270 271 ## Other tools and plug-ins3 unmodified lines275 For example:276 277 * <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.282 283 ## License2 unmodified linesmodified:docs/typer-cli.md+1 added-1 removed
270 unmodified lines271 </div>272 273 ## Options274 275-You can specify one of the following **CLI Options**:275+You can specify one of the following **CLI options**:276 277 * `--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 linesadded:tests/assets/completion_no_types_order.py+23 added
1+import typer2+3+app = typer.Typer()4+5+6+def 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+ ]15+16+17+@app.command()18+def main(name: str = typer.Option("World", autocompletion=complete)):19+ typer.echo(f"Hello {name}")20+21+22+if __name__ == "__main__":23+ app()added:tests/assets/completion_no_types.py+23 added
1+import typer2+3+app = typer.Typer()4+5+6+def 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+ ]15+16+17+@app.command()18+def main(name: str = typer.Option("World", autocompletion=complete)):19+ typer.echo(f"Hello {name}")20+21+22+if __name__ == "__main__":23+ app()modified:tests/test_completion/test_completion.py+2 added-2 removed
14 unmodified lines15 ],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.stdout22 23 10 unmodified lines34 ],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_text132 unmodified linesadded:tests/test_tutorial/test_commands/test_context/__init__.py
added:tests/test_tutorial/test_commands/test_context/test_tutorial001.py+32 added
1+import subprocess2+from commands.context import tutorial001 as mod3+4+from typer.testing import CliRunner5+6+app = mod.app7+8+runner = CliRunner()9+10+11+def 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.output16+17+18+def 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.output23+24+25+def 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.stdoutadded:tests/test_tutorial/test_commands/test_context/test_tutorial002.py+38 added
1+import subprocess2+from commands.context import tutorial002 as mod3+4+from typer.testing import CliRunner5+6+app = mod.app7+8+runner = CliRunner()9+10+11+def 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.output16+17+18+def 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.output23+24+25+def test_callback():26+ result = runner.invoke(app)27+ assert result.exit_code == 028+ assert "Initializing database" in result.output29+30+31+def 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.stdoutadded:tests/test_tutorial/test_commands/test_context/test_tutorial003.py+38 added
1+import subprocess2+from commands.context import tutorial003 as mod3+4+from typer.testing import CliRunner5+6+app = mod.app7+8+runner = CliRunner()9+10+11+def 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.output16+17+18+def 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.output23+24+25+def test_callback():26+ result = runner.invoke(app)27+ assert result.exit_code == 028+ assert "Initializing database" in result.output29+30+31+def 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.stdoutadded:tests/test_tutorial/test_commands/test_context/test_tutorial004.py+27 added
1+import subprocess2+from commands.context import tutorial004 as mod3+4+from typer.testing import CliRunner5+6+app = mod.app7+8+runner = CliRunner()9+10+11+def 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.output18+19+20+def 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.stdoutmodified:tests/test_tutorial/test_commands/test_help/test_tutorial001.py+3 added-3 removed
75 unmodified lines76 assert "Operation cancelled" in result.output77 78 79 def 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.output84 85 86 def 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.output91 92 93 def 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.output97 98 8 unmodified linesadded:tests/test_tutorial/test_options/test_callback/__init__.py
added:tests/test_tutorial/test_options/test_callback/test_tutorial001.py+33 added
1+import subprocess2+3+import typer4+from typer.testing import CliRunner5+6+from options.callback import tutorial001 as mod7+8+runner = CliRunner()9+10+app = typer.Typer()11+app.command()(mod.main)12+13+14+def test_1():15+ result = runner.invoke(app, ["--name", "Camila"])16+ assert result.exit_code == 017+ assert "Hello Camila" in result.output18+19+20+def 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.output24+25+26+def 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.stdoutadded:tests/test_tutorial/test_options/test_callback/test_tutorial003.py+52 added
1+import os2+import subprocess3+4+import typer5+from typer.testing import CliRunner6+7+from options.callback import tutorial003 as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def 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.output20+21+22+def 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.output26+27+28+def 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.stdout36+37+38+def 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.stdoutadded:tests/test_tutorial/test_options/test_callback/test_tutorial004.py+52 added
1+import os2+import subprocess3+4+import typer5+from typer.testing import CliRunner6+7+from options.callback import tutorial004 as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def 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.output20+21+22+def 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.output26+27+28+def 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.stdout36+37+38+def 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.stdoutadded:tests/test_tutorial/test_options/test_completion/__init__.py
added:tests/test_tutorial/test_options/test_completion/test_tutorial002.py+46 added
1+import os2+import subprocess3+4+import typer5+from typer.testing import CliRunner6+7+from options.autocompletion import tutorial002 as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def 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.stdout31+32+33+def test_1():34+ result = runner.invoke(app, ["--name", "Camila"])35+ assert result.exit_code == 036+ assert "Hello Camila" in result.output37+38+39+def 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.stdoutadded:tests/test_tutorial/test_options/test_completion/test_tutorial003.py+46 added
1+import os2+import subprocess3+4+import typer5+from typer.testing import CliRunner6+7+from options.autocompletion import tutorial003 as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def 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.stdout31+32+33+def test_1():34+ result = runner.invoke(app, ["--name", "Camila"])35+ assert result.exit_code == 036+ assert "Hello Camila" in result.output37+38+39+def 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.stdoutadded:tests/test_tutorial/test_options/test_completion/test_tutorial004.py+46 added
1+import os2+import subprocess3+4+import typer5+from typer.testing import CliRunner6+7+from options.autocompletion import tutorial004 as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def 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.stdout31+32+33+def test_1():34+ result = runner.invoke(app, ["--name", "Camila"])35+ assert result.exit_code == 036+ assert "Hello Camila" in result.output37+38+39+def 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.stdoutadded:tests/test_tutorial/test_options/test_completion/test_tutorial007.py+47 added
1+import os2+import subprocess3+4+import typer5+from typer.testing import CliRunner6+7+from options.autocompletion import tutorial007 as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def 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.stdout31+32+33+def 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.output38+39+40+def 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.stdoutadded:tests/test_tutorial/test_options/test_completion/test_tutorial008.py+48 added
1+import os2+import subprocess3+4+import typer5+from typer.testing import CliRunner6+7+from options.autocompletion import tutorial008 as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def 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.stderr32+33+34+def 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.output39+40+41+def 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.stdoutadded:tests/test_tutorial/test_options/test_completion/test_tutorial009.py+48 added
1+import os2+import subprocess3+4+import typer5+from typer.testing import CliRunner6+7+from options.autocompletion import tutorial009 as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def 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.stderr32+33+34+def 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.output39+40+41+def 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.stdoutadded:tests/test_tutorial/test_options/test_version/__init__.py
added:tests/test_tutorial/test_options/test_version/test_tutorial003.py+57 added
1+import os2+import subprocess3+4+import typer5+from typer.testing import CliRunner6+7+from options.version import tutorial003 as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def 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.output19+20+21+def 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.output25+26+27+def test_3():28+ result = runner.invoke(app, ["--name", "Camila"])29+ assert result.exit_code == 030+ assert "Hello Camila" in result.output31+32+33+def 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.stdout41+42+43+def 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.stdoutadded:tests/test_tutorial/test_testing/__init__.py
added:tests/test_tutorial/test_testing/test_app01.py+18 added
1+import subprocess2+3+from testing.app01 import main as mod4+from testing.app01.test_main import test_app5+6+7+def test_app01():8+ test_app()9+10+11+def 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.stdoutadded:tests/test_tutorial/test_testing/test_app02.py+18 added
1+import subprocess2+3+from testing.app02 import main as mod4+from testing.app02.test_main import test_app5+6+7+def test_app02():8+ test_app()9+10+11+def 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.stdoutadded:tests/test_tutorial/test_testing/test_app03.py+18 added
1+import subprocess2+3+from testing.app03 import main as mod4+from testing.app03.test_main import test_app5+6+7+def test_app03():8+ test_app()9+10+11+def 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.stdoutmodified:tests/test_others.py+131 added-1 removed
1+import os2+import subprocess3+from pathlib import Path4 from typing import Optional5 from unittest import mock6 7+import click8+import pytest9 import shellingham10 import typer11 import typer.completion12 from typer.main import solve_typer_info_defaults, solve_typer_info_help52 unmodified lines65 @app.command()66 def main():67 typer.echo("Hello World")68 64- 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.stdout76+77+78+def test_callback_too_many_parameters():79+ app = typer.Typer()80+81+ def name_callback(ctx, param, val1, val2):82+ pass # pragma: nocover83+84+ @app.command()85+ def main(name: str = typer.Option(..., callback=name_callback)):86+ pass # pragma: nocover87+88+ 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+ )93+94+95+def test_callback_2_untyped_parameters():96+ app = typer.Typer()97+98+ def name_callback(ctx, value):99+ typer.echo(f"info name is: {ctx.info_name}")100+ typer.echo(f"value is: {value}")101+102+ @app.command()103+ def main(name: str = typer.Option(..., callback=name_callback)):104+ typer.echo("Hello World")105+106+ result = runner.invoke(app, ["--name", "Camila"])107+ assert "info name is: main" in result.stdout108+ assert "value is: Camila" in result.stdout109+110+111+def test_callback_3_untyped_parameters():112+ app = typer.Typer()113+114+ 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}")118+119+ @app.command()120+ def main(name: str = typer.Option(..., callback=name_callback)):121+ typer.echo("Hello World")122+123+ 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.stdout127+128+129+def 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.stdout149+150+ 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.stdout157+158+159+def 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.stdout179+180+ 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.stdout187+188+189+def test_autocompletion_too_many_parameters():190+ app = typer.Typer()191+192+ def name_callback(ctx, args, incomplete, val2):193+ pass # pragma: nocover194+195+ @app.command()196+ def main(name: str = typer.Option(..., autocompletion=name_callback)):197+ pass # pragma: nocover198+199+ 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."""2 3 __version__ = "0.0.11"4 5-from click.exceptions import Abort, Exit5+from click.exceptions import Abort, BadParameter, Exit6 from click.termui import (7 clear,8 confirm,9 echo_via_pager,18 unmodified lines28 )29 30 from . import colors31 from .main import Typer, run32-from .models import Context, FileBinaryRead, FileBinaryWrite, FileText, FileTextWrite32+from .models import (33+ CallbackParam,34+ Context,35+ FileBinaryRead,36+ FileBinaryWrite,37+ FileText,38+ FileTextWrite,39+)40 from .params import Argument, Optionmodified:typer/main.py+112 added-5 removed
319 unmodified lines320 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 lines699 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 lines724 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 cover740 741 742+def 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+ )773+774+ 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: ignore787+788+ update_wrapper(wrapper, callback)789+ return wrapper790+791+792+def 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+ )828+829+ 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: ignore838+839+ update_wrapper(wrapper, callback)840+ return wrapper841+842+843 def run(function: Callable) -> Any:844 app = Typer()845 app.command()(function)846 app()modified:typer/models.py+12 added-14 removed
43 unmodified lines44 class FileBinaryWrite(io.BufferedWriter):45 pass46 47 48+class CallbackParam(click.Parameter):49+ pass50+51+52 class DefaultPlaceholder:53 """54 You shouldn't use this class directly.55 29 unmodified lines85 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 lines123 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 lines157 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 lines227 *,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 lines324 *,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 linesmodified:typer/params.py+4 added-10 removed
1 from typing import Any, Callable, List, Optional, Type, Union2 3-import click4-3 from .models import ArgumentInfo, OptionInfo4 5 6 def 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 lines102 def 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 linesmodified:mkdocs.yml+6 added
29 unmodified lines30 - 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 lines69 - 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 linesmodified:mypy.ini+2 added-3 removed
1 [mypy]2 ignore_missing_imports = True3-disallow_untyped_defs = True3 5-[mypy-tests.*]6-disallow_untyped_defs = False4+[mypy-typer.*]5+disallow_untyped_defs = Truemodified:pyproject.toml+4 added
50 unmodified lines51 "mkdocs",52 "mkdocs-material",53 "markdown-include"54 ]55+dev = [56+ "autoflake",57+ "flake8",58+]59 all = [60 "colorama",61 "shellingham"62 ]modified:README.md+13 added-7 removed
22 unmodified lines23 **Source Code**: <a href="https://github.com/tiangolo/typer" target="_blank">https://github.com/tiangolo/typer</a>24 25 ---26 27-Typer 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.27+Typer 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.28 29-**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.30-29 The key features are:30 31 * **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.36 37+## FastAPI of CLIs38+39+<a href="https://fastapi.tiangolo.com" target="_blank"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" style="width: 20%;"></a>40+41+**Typer** is <a href="https://fastapi.tiangolo.com" class="external-link" target="_blank">FastAPI</a>'s little sibling.42+43+And it's intended to be the FastAPI of CLIs.44+45 ## Requirements46 47 Python 3.6+48 43-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>.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>.50 51 ## Installation52 53 <div class="termy">170 unmodified lines224 </div>225 226 ### Recap227 222-In summary, you declare **once** the types of parameters (*arguments* and *options*) as function parameters.228+In summary, you declare **once** the types of parameters (*CLI arguments* and *CLI options*) as function parameters.229 230 You do that with standard modern Python types.231 232 You don't have to learn a new syntax, the methods or classes of a specific library, etc.30 unmodified lines263 * 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`.268 269 You can install `typer` with `colorama` and `shellingham` with `pip install typer[all]`.270 271 ## Other tools and plug-ins3 unmodified lines275 For example:276 277 * <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.282 283 ## License2 unmodified lines