Skip to content
Myr

🔥 Remove auto naming of groups added via `add_typer` based on the group's callback function name (#1052)

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

authored by Patrick Arminio · committed by GitHub · parent 45cbfcd · Browse files · 10 files+109 added−75 removed
This commit

State

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

Trailers

  • Co-authored-by: svlandeg <svlandeg@github.com>
  • Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>

Diff stats

10 files+109 added−75 removed

  • tests:+47 added−3 removed
  • other:+62 added−72 removed

10 files+109 added−75 removed

modified:docs/tutorial/subcommands/name-and-help.md+47 added-45 removed
8 unmodified lines
9```1011## Add a help text1213We can also set the `help` while adding a Typer:13We can also set the `help` text while adding a Typer:1415{* docs_src/subcommands/name_help/tutorial001.py hl[6] *}1617And then we get that help text for that command in the *CLI program*:
29 unmodified lines
47```4849</div>5051We can set the `name` and `help` in several places, each one taking precedence over the other, overriding the previous value.51We can set the `help` in several places, each one taking precedence over the other, overriding the previous value.5253Let's see those locations.5455/// tip
3 unmodified lines
59But those are documented later in another section.6061///6263## Inferring name and help from callback63## Inferring help text from callback6465### Inferring a command's name and help65### Inferring a command's help text6667When you create a command with `@app.command()`, by default, it generates the name from the function name.6869And by default, the help text is extracted from the function's docstring.
10 unmodified lines
80```8182...will create a command `create` with a help text of `Create an item`.8384### Inferring name and help from `@app.callback()`84### Inferring the help text from `@app.callback()`8586The same way, if you define a callback in a `typer.Typer()`, the help text is extracted from the callback function's docstring.8788And if that Typer app is added to another Typer app, the default name of the command is generated from the name of the callback function.8988Here's an example:8992{* docs_src/subcommands/name_help/tutorial002.py hl[6,9,10,11,12,13] *}90{* docs_src/subcommands/name_help/tutorial002.py hl[9,10,11,12,13] *}9194Notice that now we added the sub-Typer without specifying a `name` nor a `help`.92The help text for that command will be the callback function's docstring: `Manage users in the app.`.9396They are now inferred from the callback function.9798The command name will be the same callback function's name: `users`.99100And the help text for that `users` command will be the callback function's docstring: `Manage users in the app.`.10194Check it:9596<div class="termy">9798```console99// Check the main help100$ python main.py --help101110// Notice the command name "users" and the help text "Manage users in the app."102// Notice the help text "Manage users in the app."103Usage: main.py [OPTIONS] COMMAND [ARGS]...104105Options:106 --install-completion Install completion for the current shell.
19 unmodified lines
126```127128</div>129138### Name and help from callback parameter in `typer.Typer()`130/// note131140If you pass a `callback` parameter while creating a `typer.Typer(callback=some_function)` it will be used to infer the name and help text.132Before Typer 0.14.0, in addition to the help text, the command name was also inferred from the callback function name, this is no longer the case.133134///135136### Help from callback parameter in `typer.Typer()`137138If you pass a `callback` parameter while creating a `typer.Typer(callback=some_function)` it will be used to infer the help text.139140This has the lowest priority, we'll see later what has a higher priority and can override it.141142Check the code:143
8 unmodified lines
152```console153// Check the main help154$ python main.py --help155158// Notice the command name "users" and the help text "Manage users in the app."156// Notice the help text "Manage users in the app."157Usage: main.py [OPTIONS] COMMAND [ARGS]...158159Options:160 --install-completion Install completion for the current shell.
21 unmodified lines
182</div>183184### Override a callback set in `typer.Typer()` with `@app.callback()`185188The same as with normal **Typer** apps, if you pass a `callback` to `typer.Typer(callback=some_function)` and then override it with `@app.callback()`, the name and help text will be inferred from the new callback:186The same as with normal **Typer** apps, if you pass a `callback` to `typer.Typer(callback=some_function)` and then override it with `@app.callback()`, the help text will be inferred from the new callback:187188{* docs_src/subcommands/name_help/tutorial004.py hl[16,17,18,19,20] *}189192Now the name of the command will be `users` instead of `old-callback`, and the help text will be `Manage users in the app.` instead of `Old callback help.`.190Now the help text will be `Manage users in the app.` instead of `Old callback help.`.191192Check it:193194<div class="termy">
1 unmodified line
196```console197// Check the main help198$ python main.py --help199202// Notice the command name "users" and the help text "Manage users in the app."200// Notice the help text "Manage users in the app."201Usage: main.py [OPTIONS] COMMAND [ARGS]...202203Options:204 --install-completion Install completion for the current shell.
19 unmodified lines
224```225226</div>227230### Infer name and help from callback in `app.add_typer()`228### Help from callback in `app.add_typer()`229232If you override the callback in `app.add_typer()` when including a sub-app, the name and help will be inferred from this callback function.230If you override the callback in `app.add_typer()` when including a sub-app, the help will be inferred from this callback function.231234This takes precedence over inferring the name and help from a callback set in `@sub_app.callback()` and `typer.Typer(callback=sub_app_callback)`.232This takes precedence over inferring the help from a callback set in `@sub_app.callback()` and `typer.Typer(callback=sub_app_callback)`.233234Check the code:235236{* docs_src/subcommands/name_help/tutorial005.py hl[15,16,17,18,21] *}237240Now the command will be `new-users` instead of `users`. And the help text will be `I have the highland! Create some users.` instead of the previous ones.238The help text will be `I have the highland! Create some users.` instead of the previous ones.239240Check it:241242<div class="termy">
31 unmodified lines
274</div>275276### Enough inferring277280So, when inferring a name and help text, the precedence order from lowest priority to highest is:278So, when inferring help text, the precedence order from lowest priority to highest is:279280* `sub_app = typer.Typer(callback=some_function)`281* `@sub_app.callback()`282* `app.add_typer(sub_app, callback=new_function)`283286That's for inferring the name and help text from functions.284That's for inferring the help text from functions.285288But if you set the name and help text explicitly, that has a higher priority than these.286But if you set the help text explicitly, that has a higher priority than these.287288## Set the name and help289290Let's now see the places where you can set the command name and help text, from lowest priority to highest.291292/// tip293296Setting the name and help text explicitly always has a higher precedence than inferring from a callback function.294Setting the help text explicitly always has a higher precedence than inferring from a callback function.295296///297298### Name and help in `typer.Typer()`299302You could have all the callbacks and overrides we defined before, but the name and help text was inferred from the function name and docstring.300You could have all the callbacks and overrides we defined before, but the help text was inferred from the function docstring.301302If you set it explicitly, that takes precedence over inferring.303304You can set it when creating a new `typer.Typer()`:
5 unmodified lines
310The rest of the callbacks and overrides are there only to show you that they don't affect the name and help text when you set it explicitly.311312///313316We set an explicit name `exp-users`, and an explicit help `Explicit help.`.314We set an explicit help `Explicit help.`.315316So that will take precedence now.317318Check it:
31 unmodified lines
350```351352</div>353356### Name and help in `@app.callback()`354### Help text in `@app.callback()`355358Any parameter that you use when creating a `typer.Typer()` app can be overridden in the parameters of `@app.callback()`.356Many parameters that you use when creating a `typer.Typer()` app can be overridden in the parameters of `@app.callback()`.357360Continuing with the previous example, we now override the values in `@user_app.callback()`:358Continuing with the previous example, we now override the `help` in `@user_app.callback()`:359360{* docs_src/subcommands/name_help/tutorial007.py hl[24] *}361364And now the command name will be `call-users` and the help text will be `Help from callback for users.`.362And now the help text will be `Help from callback for users.`.363364Check it:365366<div class="termy">
1 unmodified line
368```console369// Check the help370$ python main.py --help371374// The command name now is call-users and the help text is "Help from callback for users.".372// The help text is now "Help from callback for users.".373Usage: main.py [OPTIONS] COMMAND [ARGS]...374375Options:376 --install-completion Install completion for the current shell.377 --show-completion Show completion for the current shell, to copy it or customize the installation.378 --help Show this message and exit.379380Commands:383 call-users Help from callback for users.381 users Help from callback for users.382385// Check the call-users command help386$ python main.py call-users --help383// Check the users command help384$ python main.py users --help385386// Notice the main help text389Usage: main.py call-users [OPTIONS] COMMAND [ARGS]...387Usage: main.py users [OPTIONS] COMMAND [ARGS]...388389 Help from callback for users.390391Options:
50 unmodified lines
442</div>443444## Recap445448The precedence to generate a command's name and help, from lowest priority to highest, is:446The precedence to generate a command's **help**, from lowest priority to highest, is:447448* Implicitly inferred from `sub_app = typer.Typer(callback=some_function)`449* Implicitly inferred from the callback function under `@sub_app.callback()`450* Implicitly inferred from `app.add_typer(sub_app, callback=some_function)`453* Explicitly set on `sub_app = typer.Typer(name="some-name", help="Some help.")`454* Explicitly set on `@sub_app.callback("some-name", help="Some help.")`455* Explicitly set on `app.add_typer(sub_app, name="some-name", help="Some help.")`451* Explicitly set on `sub_app = typer.Typer(help="Some help.")`452* Explicitly set on `app.add_typer(sub_app, help="Some help.")`453454And the priority to set the command's **name**, from lowest priority to highest, is:455456* Explicitly set on `sub_app = typer.Typer(name="some-name")`457* Explicitly set on `app.add_typer(sub_app, name="some-name")`458459So, `app.add_typer(sub_app, name="some-name", help="Some help.")` always wins.
modified:docs_src/subcommands/name_help/tutorial002.py+1 added-1 removed
1 unmodified line
23app = typer.Typer()45users_app = typer.Typer()6app.add_typer(users_app)6app.add_typer(users_app, name="users")789@users_app.callback()10def users():
12 unmodified lines
modified:docs_src/subcommands/name_help/tutorial003.py+1 added-1 removed
7 unmodified lines
8 Manage users in the app.9 """101112users_app = typer.Typer(callback=users)12users_app = typer.Typer(callback=users, name="users")13app.add_typer(users_app)141516@users_app.command()
6 unmodified lines
modified:docs_src/subcommands/name_help/tutorial004.py+1 added-1 removed
8 unmodified lines
9 """101112users_app = typer.Typer(callback=old_callback)13app.add_typer(users_app)13app.add_typer(users_app, name="users")141516@users_app.callback()17def users():
12 unmodified lines
modified:docs_src/subcommands/name_help/tutorial005.py+2 added-2 removed
7 unmodified lines
8 Old callback help.9 """101112users_app = typer.Typer(callback=old_callback)12users_app = typer.Typer(callback=old_callback, name="users")131415def new_users():16 """17 I have the highland! Create some users.18 """192021app.add_typer(users_app, callback=new_users)21app.add_typer(users_app, callback=new_users, name="new-users")222324@users_app.callback()25def users():
12 unmodified lines
modified:docs_src/subcommands/name_help/tutorial007.py+2 added-2 removed
7 unmodified lines
8 Old callback help.9 """101112users_app = typer.Typer(callback=old_callback, name="exp-users", help="Explicit help.")12users_app = typer.Typer(callback=old_callback, name="users", help="Explicit help.")131415def new_users():16 """
3 unmodified lines
2021app.add_typer(users_app, callback=new_users)222324@users_app.callback("call-users", help="Help from callback for users.")24@users_app.callback(help="Help from callback for users.")25def users():26 """27 Manage users in the app.28 """
9 unmodified lines
modified:docs_src/subcommands/name_help/tutorial008.py+1 added-1 removed
24 unmodified lines
25 help="Unlimited powder! Eh, users.",26)272829@users_app.callback("call-users", help="Help from callback for users.")29@users_app.callback(help="Help from callback for users.")30def users():31 """32 Manage users in the app.33 """
9 unmodified lines
modified:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial007.py+3 added-3 removed
12 unmodified lines
13def test_help():14 result = runner.invoke(app, ["--help"])15 assert result.exit_code == 016 assert "Commands" in result.output17 assert "call-users" in result.output17 assert "users" in result.output18 assert "Help from callback for users." in result.output192021def test_command_help():22 result = runner.invoke(app, ["call-users", "--help"])22 result = runner.invoke(app, ["users", "--help"])23 assert result.exit_code == 024 assert "Help from callback for users." in result.output252627def test_command():28 result = runner.invoke(app, ["call-users", "create", "Camila"])28 result = runner.invoke(app, ["users", "create", "Camila"])29 assert result.exit_code == 030 assert "Creating user: Camila" in result.output3132
7 unmodified lines
added:tests/test_callback_warning.py+44 added
1import pytest2import typer3from typer.testing import CliRunner45runner = CliRunner()678def test_warns_when_callback_is_not_supported():9 app = typer.Typer()1011 sub_app = typer.Typer()1213 @sub_app.callback()14 def callback():15 """This help text is not used."""1617 app.add_typer(sub_app)1819 with pytest.warns(20 match="The 'callback' parameter is not supported by Typer when using `add_typer` without a name"21 ):22 try:23 app()24 except SystemExit:25 pass262728def test_warns_when_callback_is_not_supported_added_after_add_typer():29 app = typer.Typer()3031 sub_app = typer.Typer()32 app.add_typer(sub_app)3334 @sub_app.callback()35 def callback():36 """This help text is not used."""3738 with pytest.warns(39 match="The 'callback' parameter is not supported by Typer when using `add_typer` without a name"40 ):41 try:42 app()43 except SystemExit:44 pass
modified:typer/main.py+7 added-19 removed
182 unmodified lines
183 self.registered_callback: Optional[TyperInfo] = None184185 def callback(186 self,187 name: Optional[str] = Default(None),187 *,188 cls: Optional[Type[TyperGroup]] = Default(None),189 invoke_without_command: bool = Default(False),190 no_args_is_help: bool = Default(False),
13 unmodified lines
204 rich_help_panel: Union[str, None] = Default(None),205 ) -> Callable[[CommandFunctionType], CommandFunctionType]:206 def decorator(f: CommandFunctionType) -> CommandFunctionType:207 self.registered_callback = TyperInfo(209 name=name,208 cls=cls,209 invoke_without_command=invoke_without_command,210 no_args_is_help=no_args_is_help,211 subcommand_metavar=subcommand_metavar,
174 unmodified lines
386 "Could not get a command for this Typer instance"387 ) # pragma: no cover388389392def get_group_name(typer_info: TyperInfo) -> Optional[str]:393 if typer_info.callback:394 # Priority 1: Callback passed in app.add_typer()395 return get_command_name(typer_info.callback.__name__)396 if typer_info.typer_instance:397 registered_callback = typer_info.typer_instance.registered_callback398 if registered_callback:399 if registered_callback.callback:400 # Priority 2: Callback passed in @subapp.callback()401 return get_command_name(registered_callback.callback.__name__)402 if typer_info.typer_instance.info.callback:403 return get_command_name(typer_info.typer_instance.info.callback.__name__)404 return None405406390def solve_typer_info_help(typer_info: TyperInfo) -> str:391 # Priority 1: Explicit value was set in app.add_typer()392 if not isinstance(typer_info.help, DefaultPlaceholder):393 return inspect.cleandoc(typer_info.help or "")
68 unmodified lines
462 except AttributeError:463 pass464 # Value not set, use the default465 values[name] = value.value483 if values["name"] is None:484 values["name"] = get_group_name(typer_info)466 values["help"] = solve_typer_info_help(typer_info)467 return TyperInfo(**values)468469
22 unmodified lines
492 rich_markup_mode=rich_markup_mode,493 )494 if sub_group.name:495 commands[sub_group.name] = sub_group496 elif sub_group.callback:497 import warnings498499 warnings.warn(500 "The 'callback' parameter is not supported by Typer when using `add_typer` without a name",501 stacklevel=5,502 )503 solved_info = solve_typer_info_defaults(group_info)504 (505 params,506 convertors,
630 unmodified lines