🔥 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
Provenance
- Commit
2d1a598- Tree
16c892b- Author
Patrick Arminio <patrick.arminio@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
45cbfcd
10 files changed+109 added−75 removed
modified:docs/tutorial/subcommands/name-and-help.md+47 added-45 removed
8 unmodified lines9 ```10 11 ## Add a help text12 13-We can also set the `help` while adding a Typer:13+We can also set the `help` text while adding a Typer:14 15 {* docs_src/subcommands/name_help/tutorial001.py hl[6] *}16 17 And then we get that help text for that command in the *CLI program*:29 unmodified lines47 ```48 49 </div>50 51-We can set the `name` and `help` in several places, each one taking precedence over the other, overriding the previous value.51+We can set the `help` in several places, each one taking precedence over the other, overriding the previous value.52 53 Let's see those locations.54 55 /// tip3 unmodified lines59 But those are documented later in another section.60 61 ///62 63-## Inferring name and help from callback63+## Inferring help text from callback64 65-### Inferring a command's name and help65+### Inferring a command's help text66 67 When you create a command with `@app.command()`, by default, it generates the name from the function name.68 69 And by default, the help text is extracted from the function's docstring.10 unmodified lines80 ```81 82 ...will create a command `create` with a help text of `Create an item`.83 84-### Inferring name and help from `@app.callback()`84+### Inferring the help text from `@app.callback()`85 86 The same way, if you define a callback in a `typer.Typer()`, the help text is extracted from the callback function's docstring.87 88-And 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.89-88 Here's an example:89 92-{* 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] *}91 94-Notice that now we added the sub-Typer without specifying a `name` nor a `help`.92+The help text for that command will be the callback function's docstring: `Manage users in the app.`.93 96-They are now inferred from the callback function.97-98-The command name will be the same callback function's name: `users`.99-100-And the help text for that `users` command will be the callback function's docstring: `Manage users in the app.`.101-94 Check it:95 96 <div class="termy">97 98 ```console99 // Check the main help100 $ python main.py --help101 110-// Notice the command name "users" and the help text "Manage users in the app."102+// Notice the help text "Manage users in the app."103 Usage: main.py [OPTIONS] COMMAND [ARGS]...104 105 Options:106 --install-completion Install completion for the current shell.19 unmodified lines126 ```127 128 </div>129 138-### Name and help from callback parameter in `typer.Typer()`130+/// note131 140-If you pass a `callback` parameter while creating a `typer.Typer(callback=some_function)` it will be used to infer the name and help text.132+Before 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.133 134+///135+136+### Help from callback parameter in `typer.Typer()`137+138+If you pass a `callback` parameter while creating a `typer.Typer(callback=some_function)` it will be used to infer the help text.139+140 This has the lowest priority, we'll see later what has a higher priority and can override it.141 142 Check the code:143 8 unmodified lines152 ```console153 // Check the main help154 $ python main.py --help155 158-// Notice the command name "users" and the help text "Manage users in the app."156+// Notice the help text "Manage users in the app."157 Usage: main.py [OPTIONS] COMMAND [ARGS]...158 159 Options:160 --install-completion Install completion for the current shell.21 unmodified lines182 </div>183 184 ### Override a callback set in `typer.Typer()` with `@app.callback()`185 188-The 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:186+The 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:187 188 {* docs_src/subcommands/name_help/tutorial004.py hl[16,17,18,19,20] *}189 192-Now 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.`.190+Now the help text will be `Manage users in the app.` instead of `Old callback help.`.191 192 Check it:193 194 <div class="termy">1 unmodified line196 ```console197 // Check the main help198 $ python main.py --help199 202-// Notice the command name "users" and the help text "Manage users in the app."200+// Notice the help text "Manage users in the app."201 Usage: main.py [OPTIONS] COMMAND [ARGS]...202 203 Options:204 --install-completion Install completion for the current shell.19 unmodified lines224 ```225 226 </div>227 230-### Infer name and help from callback in `app.add_typer()`228+### Help from callback in `app.add_typer()`229 232-If you override the callback in `app.add_typer()` when including a sub-app, the name and help will be inferred from this callback function.230+If you override the callback in `app.add_typer()` when including a sub-app, the help will be inferred from this callback function.231 234-This takes precedence over inferring the name and help from a callback set in `@sub_app.callback()` and `typer.Typer(callback=sub_app_callback)`.232+This takes precedence over inferring the help from a callback set in `@sub_app.callback()` and `typer.Typer(callback=sub_app_callback)`.233 234 Check the code:235 236 {* docs_src/subcommands/name_help/tutorial005.py hl[15,16,17,18,21] *}237 240-Now 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.238+The help text will be `I have the highland! Create some users.` instead of the previous ones.239 240 Check it:241 242 <div class="termy">31 unmodified lines274 </div>275 276 ### Enough inferring277 280-So, when inferring a name and help text, the precedence order from lowest priority to highest is:278+So, when inferring help text, the precedence order from lowest priority to highest is:279 280 * `sub_app = typer.Typer(callback=some_function)`281 * `@sub_app.callback()`282 * `app.add_typer(sub_app, callback=new_function)`283 286-That's for inferring the name and help text from functions.284+That's for inferring the help text from functions.285 288-But if you set the name and help text explicitly, that has a higher priority than these.286+But if you set the help text explicitly, that has a higher priority than these.287 288 ## Set the name and help289 290 Let's now see the places where you can set the command name and help text, from lowest priority to highest.291 292 /// tip293 296-Setting the name and help text explicitly always has a higher precedence than inferring from a callback function.294+Setting the help text explicitly always has a higher precedence than inferring from a callback function.295 296 ///297 298 ### Name and help in `typer.Typer()`299 302-You could have all the callbacks and overrides we defined before, but the name and help text was inferred from the function name and docstring.300+You could have all the callbacks and overrides we defined before, but the help text was inferred from the function docstring.301 302 If you set it explicitly, that takes precedence over inferring.303 304 You can set it when creating a new `typer.Typer()`:5 unmodified lines310 The 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.311 312 ///313 316-We set an explicit name `exp-users`, and an explicit help `Explicit help.`.314+We set an explicit help `Explicit help.`.315 316 So that will take precedence now.317 318 Check it:31 unmodified lines350 ```351 352 </div>353 356-### Name and help in `@app.callback()`354+### Help text in `@app.callback()`355 358-Any parameter that you use when creating a `typer.Typer()` app can be overridden in the parameters of `@app.callback()`.356+Many parameters that you use when creating a `typer.Typer()` app can be overridden in the parameters of `@app.callback()`.357 360-Continuing with the previous example, we now override the values in `@user_app.callback()`:358+Continuing with the previous example, we now override the `help` in `@user_app.callback()`:359 360 {* docs_src/subcommands/name_help/tutorial007.py hl[24] *}361 364-And now the command name will be `call-users` and the help text will be `Help from callback for users.`.362+And now the help text will be `Help from callback for users.`.363 364 Check it:365 366 <div class="termy">1 unmodified line368 ```console369 // Check the help370 $ python main.py --help371 374-// 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.".373 Usage: main.py [OPTIONS] COMMAND [ARGS]...374 375 Options: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.379 380 Commands:383- call-users Help from callback for users.381+ users Help from callback for users.382 385-// Check the call-users command help386-$ python main.py call-users --help383+// Check the users command help384+$ python main.py users --help385 386 // Notice the main help text389-Usage: main.py call-users [OPTIONS] COMMAND [ARGS]...387+Usage: main.py users [OPTIONS] COMMAND [ARGS]...388 389 Help from callback for users.390 391 Options:50 unmodified lines442 </div>443 444 ## Recap445 448-The precedence to generate a command's name and help, from lowest priority to highest, is:446+The precedence to generate a command's **help**, from lowest priority to highest, is:447 448 * 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.")`453 454+And the priority to set the command's **name**, from lowest priority to highest, is:455+456+* Explicitly set on `sub_app = typer.Typer(name="some-name")`457+* Explicitly set on `app.add_typer(sub_app, name="some-name")`458+459 So, `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 line2 3 app = typer.Typer()4 5 users_app = typer.Typer()6-app.add_typer(users_app)6+app.add_typer(users_app, name="users")7 8 9 @users_app.callback()10 def users():12 unmodified linesmodified:docs_src/subcommands/name_help/tutorial003.py+1 added-1 removed
7 unmodified lines8 Manage users in the app.9 """10 11 12-users_app = typer.Typer(callback=users)12+users_app = typer.Typer(callback=users, name="users")13 app.add_typer(users_app)14 15 16 @users_app.command()6 unmodified linesmodified:docs_src/subcommands/name_help/tutorial004.py+1 added-1 removed
8 unmodified lines9 """10 11 12 users_app = typer.Typer(callback=old_callback)13-app.add_typer(users_app)13+app.add_typer(users_app, name="users")14 15 16 @users_app.callback()17 def users():12 unmodified linesmodified:docs_src/subcommands/name_help/tutorial005.py+2 added-2 removed
7 unmodified lines8 Old callback help.9 """10 11 12-users_app = typer.Typer(callback=old_callback)12+users_app = typer.Typer(callback=old_callback, name="users")13 14 15 def new_users():16 """17 I have the highland! Create some users.18 """19 20 21-app.add_typer(users_app, callback=new_users)21+app.add_typer(users_app, callback=new_users, name="new-users")22 23 24 @users_app.callback()25 def users():12 unmodified linesmodified:docs_src/subcommands/name_help/tutorial007.py+2 added-2 removed
7 unmodified lines8 Old callback help.9 """10 11 12-users_app = typer.Typer(callback=old_callback, name="exp-users", help="Explicit help.")12+users_app = typer.Typer(callback=old_callback, name="users", help="Explicit help.")13 14 15 def new_users():16 """3 unmodified lines20 21 app.add_typer(users_app, callback=new_users)22 23 24-@users_app.callback("call-users", help="Help from callback for users.")24+@users_app.callback(help="Help from callback for users.")25 def users():26 """27 Manage users in the app.28 """9 unmodified linesmodified:docs_src/subcommands/name_help/tutorial008.py+1 added-1 removed
24 unmodified lines25 help="Unlimited powder! Eh, users.",26 )27 28 29-@users_app.callback("call-users", help="Help from callback for users.")29+@users_app.callback(help="Help from callback for users.")30 def users():31 """32 Manage users in the app.33 """9 unmodified linesmodified:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial007.py+3 added-3 removed
12 unmodified lines13 def 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.output19 20 21 def 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.output25 26 27 def 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.output31 32 7 unmodified linesadded:tests/test_callback_warning.py+44 added
1+import pytest2+import typer3+from typer.testing import CliRunner4+5+runner = CliRunner()6+7+8+def test_warns_when_callback_is_not_supported():9+ app = typer.Typer()10+11+ sub_app = typer.Typer()12+13+ @sub_app.callback()14+ def callback():15+ """This help text is not used."""16+17+ app.add_typer(sub_app)18+19+ 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+ pass26+27+28+def test_warns_when_callback_is_not_supported_added_after_add_typer():29+ app = typer.Typer()30+31+ sub_app = typer.Typer()32+ app.add_typer(sub_app)33+34+ @sub_app.callback()35+ def callback():36+ """This help text is not used."""37+38+ 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+ passmodified:typer/main.py+7 added-19 removed
182 unmodified lines183 self.registered_callback: Optional[TyperInfo] = None184 185 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 lines204 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 lines386 "Could not get a command for this Typer instance"387 ) # pragma: no cover388 389 392-def 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 None405-406-390 def 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 lines462 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)468 469 22 unmodified lines492 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 warnings498+499+ 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