Skip to content
Myr

Warn when an argument name collide with other parameters

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

Fix parsing when a parameter is named `help`, closing #2819

authored by Kevin Deldycke · committed by Kevin Deldycke · parent 8a4ce84 · Browse files · 6 files+172 added−4 removed
This commit

State

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

Diff stats

6 files+172 added−4 removed

  • tests:+119 added−1 removed
  • other:+53 added−3 removed

6 files+172 added−4 removed

modified:docs/documentation.md+1 added-1 removed
320 unmodified lines
321```322323## Help Parameter Customization324325Help parameters are automatically added by Click for any command. The default is `--help` but can be overridden by the context setting {attr}`~Context.help_option_names`. Click also performs automatic conflict resolution on the default help parameter, so if a command itself implements a parameter named `help` then the default help will not be run.325Help parameters are automatically added by Click for any command. The default is `--help` but can be overridden by the context setting {attr}`~Context.help_option_names`. Click resolves conflicts automatically: an option reusing one of the help option names takes it over, and the default help parameter is dropped once all its names are taken. A parameter merely named `help`, like `click.argument("help")`, does not disable it: both keep working independently.326327This example changes the default parameters to `-h` and `--help`328instead of just `--help`:329
14 unmodified lines
modified:src/click/core.py+44 added-2 removed
53 unmodified lines
5455F = t.TypeVar("F", bound="t.Callable[..., t.Any]")56V = t.TypeVar("V")5758# Reserved storage name of the automatic help option. No user parameter is59# expected to claim it.60_HELP_OPTION_STORAGE_NAME = "_click_default_help"616263def _complete_visible_commands(64 ctx: Context, incomplete: str65) -> cabc.Iterator[tuple[str, Command]]:66 """List all the subcommands of a group that start with the
1055 unmodified lines
1122 ),1123 stacklevel=3,1124 )11251126 # Options may deliberately share a storage name to compete for1127 # the same value (feature switches), but an argument sharing a1128 # name silently overwrites the other parameter's value.1129 names_counter = Counter(param.name for param in params)1130 duplicate_names = (1131 name for name, count in names_counter.items() if count > 11132 )11331134 for duplicate_name in duplicate_names:1135 sharers = [param for param in params if param.name == duplicate_name]11361137 if help_option in sharers:1138 warnings.warn(1139 (1140 f"The name {duplicate_name!r} is reserved for the "1141 "automatic help option. Give the parameter a "1142 "different name."1143 ),1144 stacklevel=3,1145 )1146 elif any(isinstance(param, Argument) for param in sharers):1147 warnings.warn(1148 (1149 f"The name {duplicate_name!r} is used by an argument "1150 "and another parameter. They will overwrite each "1151 "other's value during parsing. Give each parameter "1152 "a unique name."1153 ),1154 stacklevel=3,1155 )11561157 return params11581159 def format_usage(self, ctx: Context, formatter: HelpFormatter) -> None:1160 """Writes the usage line into the formatter.
26 unmodified lines
1187 """Returns the help option object.11881189 Skipped if :attr:`add_help_option` is ``False``.11901191 .. versionchanged:: 8.5.01192 The help option stores its value under the reserved name1193 ``_click_default_help``, so a parameter named ``help`` no1194 longer breaks parsing.11951196 .. versionchanged:: 8.1.81197 The help option is now cached to avoid creating it multiple times.1198 """1199 help_option_names = self.get_help_option_names(ctx)
8 unmodified lines
1208 if self._help_option is None:1209 # Avoid circular import.1210 from .decorators import help_option12111172 # Apply help_option decorator and pop resulting option1173 help_option(*help_option_names)(self)1212 # The help option never exposes its value, so it uses a reserved1213 # storage name, keeping it clear of user parameters (like an1214 # argument named "help") that would otherwise clobber its value.1215 help_option(*help_option_names, _HELP_OPTION_STORAGE_NAME)(self)1216 self._help_option = self.params.pop() # type: ignore[assignment]12171218 return self._help_option1219
2504 unmodified lines
modified:tests/test_basic.py+82 added
26 unmodified lines
27 assert "I EXECUTED" in result.output28 assert result.exit_code == 0293031@pytest.mark.parametrize(32 ("help_names", "params", "args", "expected_output"),33 [34 (["--help"], [], [], "\n"),35 (["--help"], [click.Argument(["help"])], ["value"], "value\n"),36 (37 ["--help"],38 [click.Option(["--assist", "help"])],39 ["--assist", "value"],40 "value\n",41 ),42 (["--man"], [click.Option(["--foo", "man"])], ["--foo", "value"], "value\n"),43 ],44 ids=["no-collision", "argument", "option", "custom-flags"],45)46def test_param_named_help(runner, help_names, params, args, expected_output):47 """User parameters never clash with the automatic help option, which48 stores its value under the reserved ``_click_default_help`` name.4950 https://github.com/pallets/click/issues/281951 """52 cli = click.Command(53 "cli",54 context_settings={"help_option_names": help_names},55 params=params,56 callback=lambda **kwargs: click.echo(next(iter(kwargs.values()), None)),57 )5859 ctx = click.Context(cli, help_option_names=help_names)60 help_option = cli.get_help_option(ctx)61 assert help_option is not None62 assert help_option.name == "_click_default_help"6364 result = runner.invoke(cli, args)65 assert result.output == expected_output66 assert result.exit_code == 06768 result = runner.invoke(cli, [help_names[0]])69 assert "Show this message and exit." in result.output70 assert result.exit_code == 0717273def test_param_squatting_help_option_name(runner):74 """Claiming the reserved storage name of the automatic help option75 triggers a warning.76 """7778 @click.command()79 @click.argument("_click_default_help")80 def cli(_click_default_help):81 click.echo(_click_default_help)8283 with pytest.warns(UserWarning, match="reserved for the automatic help option"):84 result = runner.invoke(cli, ["value"])8586 # The collision still breaks parsing, but no longer silently.87 assert result.exit_code == 2888990def test_option_reusing_help_flag(runner):91 """An option reusing the ``--help`` flag replaces the automatic help92 option entirely.9394 https://github.com/pallets/click/issues/281995 """9697 @click.command()98 @click.option("--help", default="default value")99 def cli(help):100 click.echo(help)101102 assert cli.get_help_option(click.Context(cli)) is None103104 result = runner.invoke(cli, [])105 assert result.output == "default value\n"106 assert result.exit_code == 0107108 result = runner.invoke(cli, ["--help", "custom"])109 assert result.output == "custom\n"110 assert result.exit_code == 0111112113def test_repr():114 @click.command()115 def command():116 pass
848 unmodified lines
modified:tests/test_info_dict.py+1 added-1 removed
7 unmodified lines
8BOOL_PARAM_TYPE = (click.BOOL, {"param_type": "Bool", "name": "boolean"})9HELP_OPTION = (10 None,11 {12 "name": "help",12 "name": "_click_default_help",13 "param_type_name": "option",14 "opts": ["--help"],15 "secondary_opts": [],16 "type": BOOL_PARAM_TYPE[1],
299 unmodified lines
modified:tests/test_options.py+36 added
3322 unmodified lines
3323 with pytest.warns(UserWarning, match="used more than once"):3324 runner.invoke(cli, [])332533263327def test_argument_sharing_param_name_warning(runner):3328 """An argument sharing its storage name with an option makes both3329 silently overwrite each other's value, which triggers a warning.3330 """33313332 @click.command()3333 @click.option("--foo", "target")3334 @click.argument("target")3335 def cli(target):3336 click.echo(target, nl=False)33373338 with pytest.warns(UserWarning, match="'target' is used by an argument"):3339 result = runner.invoke(cli, ["--foo", "from_option", "from_argument"])33403341 # The value parsed by the option is lost to the argument's.3342 assert result.output == "from_argument"3343 assert result.exit_code == 0334433453346def test_options_sharing_name_no_warning(runner):3347 """Options deliberately sharing a storage name (feature switches) are3348 exempt from the duplicate-name warning. Warnings are errors in this3349 suite, so a clean run proves none fired.3350 """33513352 @click.command()3353 @click.option("--upper", "transformation", flag_value="upper")3354 @click.option("--lower", "transformation", flag_value="lower")3355 def cli(transformation):3356 click.echo(transformation, nl=False)33573358 result = runner.invoke(cli, ["--upper"])3359 assert result.output == "upper"3360 assert result.exit_code == 0336133623363@pytest.mark.parametrize(3364 ("args", "expected"),3365 [3366 (["--with-xyz", "--with-xyz"], True),
185 unmodified lines
modified:CHANGES.md+8 added
15 unmodified lines
16 does not. The feature set of {func}`version_option` is now frozen; see17 [discussion #3527](https://github.com/pallets/click/discussions/3527). {pr}`3581`18- `style()` and `secho()` no longer silently drop the 256-color index `0`19 (black) passed as `fg` or `bg`, and now validate color arguments. {pr}`3677`20- The automatic help option stores its value under the reserved name21 `_click_default_help` instead of `help`, so a parameter named `help` no22 longer breaks parsing. The new name is visible in23 {meth}`Command.to_info_dict` output. Parameters that overwrite each other's24 value trigger a warning: an argument sharing its name with another25 parameter, or any parameter claiming the reserved name. Options may still26 share a name to compete for the same value (feature switches).27 {issue}`2819` {pr}`3678`2829## Version 8.4.23031Released 2026-06-24
1561 unmodified lines