Skip to content
Myr

Add help parameter to arguments

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

Closes #2983

authored by Yuri Shevtsov · committed by Kevin Deldycke · parent 1a994ad · Browse files · 6 files+184 added−7 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: Rowlando13 <67291205+Rowlando13@users.noreply.github.com>
  • Co-authored-by: Kevin Deldycke <kdeldycke@users.noreply.github.com>

Diff stats

6 files+184 added−7 removed

  • tests:+128 added−0 removed
  • other:+56 added−7 removed

6 files+184 added−7 removed

modified:docs/arguments.md+4 added-1 removed
modified:docs/documentation.md+7 added-5 removed
13 unmodified lines
14```{eval-rst}15.. click:example::1617 @click.command()18 @click.argument('name')18 @click.argument('name', help='The name to print')19 @click.option('--count', default=1, help='number of greetings')20 def hello(name: str, count: int):21 """This script prints hello and a name one or more times."""22 for x in range(count):
89 unmodified lines
112(documenting-arguments)=113114## Documenting Arguments115116{class}`click.argument` does not take a `help` parameter. This follows the Unix Command Line Tools convention of using arguments only for necessary things and documenting them in the command help text117by name. This should then be done via the docstring.116{class}`click.argument` accepts an optional `help` parameter that is shown in117the ``Positional arguments`` section of the help page. You can still document118arguments in the command docstring, especially when you want to describe them119in the main help text by name.120121A brief example:122123```{eval-rst}124.. click:example::125126 @click.command()125 @click.argument('filename')127 @click.argument('filename', help='The file to print.')128 def touch(filename):129 """Print FILENAME."""130 click.echo(filename)131132.. click:run::133 invoke(touch, args=['--help'])134```135134Or more explicitly:136Or more explicitly in the docstring:137138```{eval-rst}139.. click:example::140
203 unmodified lines
modified:src/click/core.py+43 added-1 removed
1170 unmodified lines
1171 This calls the following methods:11721173 - :meth:`format_usage`1174 - :meth:`format_help_text`1175 - :meth:`format_arguments`1176 - :meth:`format_options`1177 - :meth:`format_epilog`1178 """1179 self.format_usage(ctx, formatter)1180 self.format_help_text(ctx, formatter)1181 self.format_arguments(ctx, formatter)1182 self.format_options(ctx, formatter)1183 self.format_epilog(ctx, formatter)11841185 def format_help_text(self, ctx: Context, formatter: HelpFormatter) -> None:
18 unmodified lines
1204 """Writes all the options into the formatter if they exist."""1205 opts = []1206 for param in self.get_params(ctx):1207 rv = param.get_help_record(ctx)1206 if rv is not None:1208 if rv is not None and not isinstance(param, Argument):1209 opts.append(rv)12101211 if opts:1212 with formatter.section(_("Options")):1213 formatter.write_dl(opts)12141215 def format_arguments(self, ctx: Context, formatter: HelpFormatter) -> None:1216 """Writes the arguments that have a help record into the formatter."""1217 args = []1218 for param in self.get_params(ctx):1219 rv = param.get_help_record(ctx)1220 if rv is not None and isinstance(param, Argument):1221 args.append(rv)12221223 if args:1224 with formatter.section(_("Positional arguments")):1225 formatter.write_dl(args)12261227 def format_epilog(self, ctx: Context, formatter: HelpFormatter) -> None:1228 """Writes the epilog into the formatter if it exists."""1229 if self.epilog:1230 epilog = inspect.cleandoc(self.epilog)
2232 unmodified lines
3463 provide fewer features than options but can have infinite ``nargs``3464 and are required by default.34653466 All parameters are passed onwards to the constructor of :class:`Parameter`.34673468 :param help: the help string.34693470 .. versionchanged:: 8.53471 Added the ``help`` parameter.3472 """34733474 param_type_name = "argument"34753476 def __init__(3477 self,3478 param_decls: cabc.Sequence[str],3479 required: bool | None = None,3480 help: str | None = None,3481 **attrs: t.Any,3482 ) -> None:3483 # Auto-detect the requirement status of the argument if not explicitly set.3484 if required is None:
7 unmodified lines
34923493 if "multiple" in attrs:3494 raise TypeError("__init__() got an unexpected keyword argument 'multiple'.")34953496 deprecated = attrs.get("deprecated", False)34973498 if help:3499 help = inspect.cleandoc(help)35003501 if deprecated:3502 label = _format_deprecated_label(deprecated)3503 help = f"{help} {label}" if help else label35043505 self.help = help35063507 super().__init__(param_decls, required=required, **attrs)35083509 def to_info_dict(self) -> dict[str, t.Any]:3510 info_dict = super().to_info_dict()3511 info_dict.update(help=self.help)3512 return info_dict35133514 @property3515 def human_readable_name(self) -> str:3516 if self.metavar is not None:3517 return self.metavar
34 unmodified lines
35523553 def get_usage_pieces(self, ctx: Context) -> list[str]:3554 return [self.make_metavar(ctx)]35553556 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:3557 if self.help is None:3558 return None35593560 return self.make_metavar(ctx), self.help35613562 def get_error_hint(self, ctx: Context | None) -> str:3563 if ctx is not None:3564 return f"'{self.make_metavar(ctx)}'"3565 return f"'{self.human_readable_name}'"
27 unmodified lines
modified:tests/test_arguments.py+88 added
293 unmodified lines
294 assert result.exit_code == 0295 assert result.output == "test\n"296297298def test_argument_help(runner):299 @click.command()300 @click.argument("name", help="The name to print")301 @click.option("--count", default=1, help="number of greetings")302 def cli(name, count):303 pass304305 result = runner.invoke(cli, ["--help"])306 assert result.exit_code == 0, result.output307 assert "Positional arguments:" in result.output308 assert "NAME" in result.output309 assert "The name to print" in result.output310 assert "Options:" in result.output311 assert "number of greetings" in result.output312 assert result.output.index("Positional arguments:") < result.output.index(313 "Options:"314 )315316317def test_argument_help_options_only_no_arguments_section(runner):318 @click.command()319 @click.option("--count", default=1, help="number of greetings")320 def cli(count):321 pass322323 result = runner.invoke(cli, ["--help"])324 assert result.exit_code == 0, result.output325 assert "Positional arguments:" not in result.output326 assert "Options:" in result.output327 assert "number of greetings" in result.output328329330def test_argument_help_optional_metavar(runner):331 @click.command()332 @click.argument("name", required=False, default="", help="The name to print")333 def cli(name):334 pass335336 result = runner.invoke(cli, ["--help"])337 assert result.exit_code == 0, result.output338 assert "[NAME]" in result.output339 assert "The name to print" in result.output340341342def test_deprecated_usage(runner):343 @click.command()344 @click.argument("f", required=False, deprecated=True)345 def cli(f):
29 unmodified lines
375 assert result.exit_code == 0376 assert result.output.splitlines()[0] == f"Usage: cli [OPTIONS] {expected}"377378379@pytest.mark.parametrize(380 ("deprecated", "expected_label"),381 [(True, "(DEPRECATED)"), ("use g instead", "(DEPRECATED: use g instead)")],382)383def test_deprecated_usage_help_record(runner, deprecated, expected_label):384 @click.command()385 @click.argument("f", required=False, deprecated=deprecated, help="path to the file")386 def cli(f):387 click.echo(f)388389 result = runner.invoke(cli, ["--help"])390 assert result.exit_code == 0, result.output391 assert "Positional arguments:" in result.output392 assert "[F!]" in result.output393 assert f"path to the file {expected_label}" in result.output394395396def test_deprecated_usage_help_record_without_help(runner):397 @click.command()398 @click.argument("f", required=False, deprecated=True)399 def cli(f):400 click.echo(f)401402 result = runner.invoke(cli, ["--help"])403 assert result.exit_code == 0, result.output404 # Deprecation alone produces a help row with just the deprecation label.405 assert "Positional arguments:" in result.output406 assert "(DEPRECATED)" in result.output407408409@pytest.mark.parametrize(410 ("deprecated", "expected"),411 [(True, "(DEPRECATED)"), ("USE B INSTEAD", "(DEPRECATED: USE B INSTEAD)")],412)413@pytest.mark.parametrize("help_text", ["", None])414def test_deprecated_empty_help_no_leading_space(help_text, deprecated, expected):415 """An argument with empty or missing help text must not gain a stray leading416 space before the deprecation label.417 """418 arg = click.Argument(["foo"], required=False, help=help_text, deprecated=deprecated)419 ctx = click.Context(click.Command("cli"))420 assert arg.get_help_record(ctx)[1] == expected421422423@pytest.mark.parametrize("deprecated", [True, "USE B INSTEAD"])424def test_deprecated_warning(runner, deprecated):425 @click.command()426 @click.argument(
317 unmodified lines
modified:tests/test_info_dict.py+40 added
38 unmodified lines
39 "nargs": 1,40 "multiple": False,41 "default": None,42 "envvar": None,43 "help": None,44 },45)46NUMBER_OPTION = (47 click.Option(["-c", "--count", "number"], default=1),
225 unmodified lines
273 class TestType(click.ParamType):274 pass275276 assert TestType().to_info_dict()["name"] == "TestType"277278279@pytest.mark.parametrize(280 ("help_in", "help_out"),281 [282 pytest.param(None, None, id="None"),283 pytest.param("", "", id="empty"),284 pytest.param("single line", "single line", id="single-line"),285 pytest.param(286 "\n first line\n second line\n ",287 "first line\nsecond line",288 id="multi-line",289 ),290 ],291)292def test_argument_to_info_dict_help(help_in, help_out):293 arg = click.Argument(["name"], help=help_in)294 assert arg.to_info_dict()["help"] == help_out295296297def test_argument_to_info_dict_nargs():298 arg = click.Argument(["files"], nargs=-1, help="files to process")299 info = arg.to_info_dict()300 assert info["nargs"] == -1301 assert info["help"] == "files to process"302303304def test_command_to_info_dict_multiple_arguments():305 @click.command()306 @click.argument("src", help="source path")307 @click.argument("dst", help="destination path")308 def cli(src, dst):309 pass310311 ctx = click.Context(cli)312 params = cli.to_info_dict(ctx)["params"]313 args = [p for p in params if p["param_type_name"] == "argument"]314 assert [p["name"] for p in args] == ["src", "dst"]315 assert [p["help"] for p in args] == ["source path", "destination path"]
modified:CHANGES.rst+2 added
5 unmodified lines
6Unreleased78- Supported versions of Windows enable ANSI terminal styles by default.9 Colorama is no longer a dependency and is not used. :issue:`2986` :pr:`3505`10- :class:`Argument` accepts a ``help`` parameter, and help output includes11 a ``Positional arguments`` section when argument help is available. :issue:`2983` :pr:`3473`121314Version 8.4.215-------------
1491 unmodified lines