Landed
Add `Parameter.spec` and deprecate `human_readable_name` (#3877)
Landed as 2247b35
authored by Rowlando13 · committed by the platform · parents 06b2a67, 9f0bcdf · Browse files · 7 files·+266 added−26 removed
7 files changed+266 added−26 removed
modified:docs/parameters.md+34 added-12 removed
29 unmodified lines30313233343536343538393637383940414243444545464748495046474849505152535454555657585960616263646566676869707172737475767729 unmodified lines(parameter-names)=
## Parameter Names
Parameters (options and arguments) have a name that will be used asthe Python argument name when calling the decorated function withvalues.Three distinct strings designate a parameter, and each one has its own audience:
In the example, the argument's name is `filename`. The name must match the python arg name. To provide a different name for use in help text, see {ref}`doc-meta-variables`.The option's names are `-t` and `--times`. More names are available for options and are covered in {ref}`options`.- `decls` are the declarations you pass to the decorator. Click parses them to derive every other string in this section.- `spec` is what the user reads in `--help` and types on the command line. Read it from {attr}`Parameter.spec`, or from {meth}`Parameter.get_help_spec` for the longer form the help page lays out in its left column.- `name` is what Click uses internally to identify the parameter. It is used as a Python argument and is passed to the decorated function. Read it from {attr}`Parameter.name`.
Click also keeps the parsed declarations on the parameter. {attr}`Parameter.opts` holds every spelling an option answers to, and {attr}`Parameter.secondary_opts` the ones that set a boolean flag to false.
```{eval-rst}.. click:example::
@click.command() @click.argument('filename') @click.option('-t', '--times', type=int) def multi_echo(filename, times): """Print value filename multiple times.""" for x in range(times): click.echo(filename) @click.argument('recipe') @click.option('-g', '--gluten-free/--no-gluten-free', default=False) def bake(recipe, gluten_free): """Bake the RECIPE, with or without gluten.""" note = 'no gluten' if gluten_free else 'with gluten' click.echo(f'{recipe}: {note}')
.. click:run::
invoke(multi_echo, ['--times=3', 'index.txt'], prog_name='multi_echo') invoke(bake, ['--gluten-free', 'brioche'], prog_name='bake')
.. click:run::
invoke(bake, ['--help'], prog_name='bake')```
The example holds one argument and one option. The table lists all five strings for each of them:
| | `@click.argument('recipe')` | `@click.option('-g', '--gluten-free/--no-gluten-free')` ||---|---|---|| `decls` | `('recipe',)` | `('-g', '--gluten-free/--no-gluten-free')` || `spec` | `RECIPE` | `--gluten-free` || `name` | `recipe` | `gluten_free` || `opts` | `['recipe']` | `['-g', '--gluten-free']` || `secondary_opts` | `[]` | `['--no-gluten-free']` |
Click derives an option's `name` from the declaration with the longest prefix, so it picks `--gluten-free` over `-g`. It then lowercases that declaration and replaces its dashes with underscores, which gives `gluten_free`. The name must match the Python argument name of the decorated function. More declarations are available for options and are covered in {ref}`options`.
An argument has a single declaration. It becomes the only entry in `opts`, and `name` is that declaration lowercased, with dashes replaced by underscores. The `spec` is the name in upper case. `secondary_opts` stays empty, since the parser binds an argument by name and never matches a spelling. To choose the spec an argument shows in help text, see {ref}`doc-meta-variables`.
The help page above shows each `spec` where the user reads it: `RECIPE` in the usage line, and `-g, --gluten-free / --no-gluten-free` in the left column of the options list, which is the longer form {meth}`Parameter.get_help_spec` returns.modified:docs/upgrade-guides.md+2 added-1 removed
14 unmodified lines15 For each deprecation, provide a brief explanation, and direct users to new function / class if available.16 - A parameter name that is not a valid Python identifier, or that is a [Python keyword](https://docs.python.org/3/reference/lexical_analysis.html#keywords), is deprecated and raises `TypeError` in 9.0. [`str.isidentifier()`](https://docs.python.org/3/library/stdtypes.html#str.isidentifier) decides the first case, so `click.argument("0foo")` fails it. It accepts a keyword, so `click.option("--from")` names a parameter `from`, which no callback can declare. [Soft keywords](https://docs.python.org/3/reference/lexical_analysis.html#soft-keywords) such as `match` and `type` are contextual and unaffected, and `--True` and `--None` lower case out of the keyword set. To migrate, pass an explicit name (`click.option("--from", "source")`, `click.option("--0-file", "zero_file")`). An argument takes one declaration and has no explicit-name channel, so rename it and pass `metavar` to keep its old display (`click.argument("zero_file", metavar="0-FILE")`). See [#3827](https://github.com/pallets/click/pull/3827) and [#3866](https://github.com/pallets/click/pull/3866).17 - An option name written as a Python identifier is deprecated when it is not already lower cased: `click.option("--x", "Foo_Bar")` names `foo_bar` rather than `Foo_Bar`. To migrate, spell the name the way the callback declares it. See [#3827](https://github.com/pallets/click/pull/3827).18 - `CliRunner.isolated_filesystem()` is deprecated and will be removed in Click 9.0. The helper predates Python 3 and modern pytest, and it relies on `os.chdir`, which mutates process-global state and is therefore not thread-safe. Replace it with a temporary directory (`tempfile.TemporaryDirectory`, or pytest's `tmp_path` fixture) and pass absolute paths to the command instead of relying on the current working directory. To run commands in parallel, use process-based isolation (such as `pytest-xdist`) rather than threads, since `CliRunner.invoke()` also redirects the process-global standard streams and other interpreter-wide state. See [#3700](https://github.com/pallets/click/issues/3700), [#3501](https://github.com/pallets/click/issues/3501) and the [testing guide](testing.md#running-tests-in-parallel).19+- `Parameter.human_readable_name` is deprecated and will be removed in Click 9.0. Use `Parameter.spec` instead, which returns how the user spells the parameter on the command line. For an argument the two agree, since both return the metavar. For an option the old property returned the internal `name`, so the value changes from `my_option` to `--my-option`. Click no longer reads the property, so an override in a subclass has no effect: override `Parameter.spec` instead. Defining a subclass that still overrides `human_readable_name` emits a `DeprecationWarning`. See the [parameter names](parameters.md#parameter-names) section for the three strings that designate a parameter.20 21 ### Removals with prior deprecation22 23 For each removal, provide a brief explanation, and direct users to new function / class if available. If possible, deprecate and remove in 10.0.0, rather than removing outright.5 unmodified lines29 - TBD30 31 ### Changes32 32-- TBD33+- Error messages and deprecation warnings name an option by its spec rather than its internal name, so `The option 'my_option' is deprecated.` now reads `The option '--my-option' is deprecated.` Tests asserting on the old wording need updating.34 35 ### Fixes36 37 - TBDmodified:src/click/core.py+121 added-12 removed
103 unmodified lines104 """Write the final abort message to standard error."""105 echo(_("Aborted!"), file=sys.stderr)106 107 108-def _outside_click_stacklevel() -> int:108+def _outside_click_stacklevel(skip: cabc.Container[str] = ()) -> int:109 """Depth of the first stack frame outside Click.110 111+ :param skip: Other module names to walk past. ``abc`` is one: it sits112+ between ``__init_subclass__`` and the ``class`` statement that the113+ warning must point at.114+115 .. versionadded:: 8.6.0116 """117 frame: FrameType | None = sys._getframe(1)118 level = 1119 120 while frame is not None:121 module = frame.f_globals.get("__name__", "")122 119- if module != "click" and not module.startswith("click."):123+ if module != "click" and not module.startswith("click.") and module not in skip:124 return level125 126 frame = frame.f_back127 level += 12117 unmodified lines2245 intentionally not finalized.2246 2247 Some settings are supported by both options and arguments.2248 2249+ Three distinct strings designate a parameter, each with its own audience:2250+2251+ ``decls``2252+ What the developer passes to the constructor as ``param_decls``.2253+ ``spec``2254+ What the user reads in ``--help`` and types on the command line. See2255+ :attr:`spec` and :meth:`get_help_spec`.2256+ ``name``2257+ What Click uses internally to identify the parameter and to pass its2258+ value to the command callback. See :attr:`name`.2259+2260 :param param_decls: the parameter declarations for this option or2261 argument. This is a list of flags or argument2262 names.2263 :param type: the type that should be used. Either a :class:`ParamType`84 unmodified lines2348 2349 param_type_name = "parameter"2350 2351 name: str2352+ """What Click uses internally to identify the parameter, and the Python2353+ argument name it passes to the command callback. Click derives it from the2354+ declarations, lower cased and with dashes replaced by underscores. An2355+ :class:`Option` takes the declaration with the longest prefix, so2356+ ``"-t", "--times"`` names ``times``, while an :class:`Argument` takes its2357+ single declaration.2358+ """2359 opts: list[str]2360+ """Every command-line spelling that designates this parameter.2361+2362+ For an :class:`Option` these are the prefixed declarations the parser2363+ matches, in declaration order: ``["-t", "--times"]``. :attr:`spec` is the2364+ canonical one.2365+2366+ For an :class:`Argument` this holds the single declaration the developer2367+ wrote, ``["filename"]``. The parser never reads it: it binds the value by2368+ :attr:`name`. The string the user reads is :attr:`spec`, ``FILENAME``.2369+ """2370 secondary_opts: list[str]2371+ """The spellings that set a boolean :class:`Option` to ``False``, taken from2372+ the right side of a ``--color/--no-color`` declaration. Always empty for an2373+ :class:`Argument`.2374+ """2375 # `Parameter.type` is annotated in `__init__` to avoid confusing mypy2376 required: bool2377 callback: t.Callable[[Context, Parameter, t.Any], t.Any] | None2378 nargs: int9 unmodified lines2388 )2389 deprecated: bool | str2390 help: str | None2391 2392+ def __init_subclass__(cls, **kwargs: t.Any) -> None:2393+ super().__init_subclass__(**kwargs)2394+2395+ if "human_readable_name" in cls.__dict__:2396+ import warnings2397+2398+ warnings.warn(2399+ f"{cls.__name__} overrides 'human_readable_name'. Click no"2400+ " longer reads that property. Override 'spec' instead. Click"2401+ " will remove 'human_readable_name' in 9.0.",2402+ DeprecationWarning,2403+ stacklevel=_outside_click_stacklevel(skip=("abc",)),2404+ )2405+2406 def __init__(2407 self,2408 param_decls: cabc.Sequence[str] | None = None,2409 type: types.ParamType[t.Any] | t.Any | None = None,71 unmodified lines2481 )2482 2483 if required and deprecated:2484 raise ValueError(2435- f"The {self.param_type_name} '{self.human_readable_name}' "2485+ f"The {self.param_type_name} '{self.spec}' "2486 "is deprecated and still required. A deprecated "2487 f"{self.param_type_name} cannot be required."2488 )2489 76 unmodified lines2566 stacklevel=_outside_click_stacklevel(),2567 )2568 2569 @property2570+ def spec(self) -> str:2571+ """Returns how the user spells this parameter on the command line.2572+2573+ This is the declaration with the longest prefix, so an option declared2574+ as ``"-t", "--times"`` returns ``--times``. Click derives :attr:`name`2575+ from that same declaration, unless the developer passed an explicit2576+ name. A parameter without declarations returns its :attr:`name`.2577+2578+ .. versionadded:: 8.6.02579+ """2580+ if not self.opts:2581+ return self.name2582+2583+ return max(self.opts, key=lambda opt: len(_split_opt(opt)[0]))2584+2585+ @property2586 def human_readable_name(self) -> str:2521- """Returns the human readable name of this parameter. This is the2522- same as the name for options, but the metavar for arguments.2587+ """Returns how the user spells this parameter on the command line.2588+2589+ .. deprecated:: 8.6.02590+ Will be removed in Click 9.0. Use :attr:`spec` instead. For an2591+ option this returned the internal :attr:`name`, so the value2592+ changes from ``times`` to ``--times``. Click no longer reads this2593+ property, so an override in a subclass has no effect.2594 """2524- return self.name2595+ import warnings2596 2597+ warnings.warn(2598+ "'human_readable_name' is deprecated and will be removed in Click"2599+ " 9.0. Use 'spec' instead.",2600+ DeprecationWarning,2601+ stacklevel=2,2602+ )2603+ return self.spec2604+2605+ def get_help_spec(self, ctx: Context) -> str:2606+ """Returns the left column of this parameter's help record.2607+2608+ This implementation returns :attr:`spec`. :class:`Option` returns every2609+ spelling, plus the metavar when the option takes a value.2610+ :class:`Argument` returns its metavar, which already carries the markers2611+ for an optional, repeated or deprecated value.2612+2613+ Unlike ``get_help_record()``, the spec is produced even when the2614+ parameter is left out of the help page, like a hidden option.2615+2616+ .. versionadded:: 8.6.02617+ """2618+ return self.spec2619+2620 def make_metavar(self, ctx: Context) -> str:2621 if self.metavar is not None:2622 return self.metavar2623 342 unmodified lines2966 "DeprecationWarning: The {param_type} {name!r} is deprecated."2967 "{extra_message}"2968 ).format(2969 param_type=self.param_type_name,2876- name=self.human_readable_name,2970+ name=self.spec,2971 extra_message=_format_deprecated_suffix(self.deprecated),2972 )2973 echo(style(message, fg="red"), err=True)2974 51 unmodified lines3026 3027 .. versionchanged:: 8.4.03028 ``ctx`` can be ``None``.3029 """2936- hint_list = self.opts or [self.human_readable_name]3030+ hint_list = self.opts or [self.spec]3031 return " / ".join(f"'{x}'" for x in hint_list)3032 3033 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]:3034 """Return a list of completions for the incomplete value. If a893 unmodified lines3928 3929 super().__init__(param_decls, required=required, help=help, **attrs)3930 3931 @property3838- def human_readable_name(self) -> str:3932+ def spec(self) -> str:3933+ """Returns the argument's metavar, which is how the user reads it in3934+ ``--help``. An argument has no flag to spell, so this is the3935+ :attr:`metavar` if one was given, and the uppercased :attr:`name`3936+ otherwise.3937+3938+ .. versionadded:: 8.6.03939+ """3940 if self.metavar is not None:3941 return self.metavar3942 return self.name.upper()3943 39 unmodified lines3983 3984 def get_usage_pieces(self, ctx: Context) -> list[str]:3985 return [self.make_metavar(ctx)]3986 3987+ def get_help_spec(self, ctx: Context) -> str:3988+ """Returns the left column of the argument's help record: its metavar,3989+ like ``FILENAME`` or ``[FILENAME]``.3990+3991+ .. versionadded:: 8.6.03992+ """3993+ return self.make_metavar(ctx)3994+3995 def get_help_record(self, ctx: Context) -> tuple[str, str]:3996 """Returns the argument's help row: its metavar and its help text.3997 3998 Unlike :meth:`Option.get_help_record`, this never returns ``None``. An3 unmodified lines4002 .. versionchanged:: 8.5.14003 Always returns a tuple. It used to return ``None`` when ``help`` was4004 not set.4005 """3897- return self.make_metavar(ctx), self.help or ""4006+ return self.get_help_spec(ctx), self.help or ""4007 4008 def get_error_hint(self, ctx: Context | None) -> str:4009 if ctx is not None:3901- return f"'{self.make_metavar(ctx)}'"3902- return f"'{self.human_readable_name}'"4010+ return f"'{self.get_help_spec(ctx)}'"4011+ return f"'{self.spec}'"4012 4013 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:4014 parser.add_argument(dest=self.name, nargs=self.nargs, obj=self)4015 23 unmodified linesmodified:tests/test_arguments.py+30 added
861 unmodified lines862 assert "(DEPRECATED)" in result.output863 864 865 @pytest.mark.parametrize(866+ ("kwargs", "expected_spec", "expected_help_spec"),867+ [868+ ({}, "FILENAME", "FILENAME"),869+ ({"required": False}, "FILENAME", "[FILENAME]"),870+ ({"nargs": -1}, "FILENAME", "[FILENAME]..."),871+ ({"metavar": "<file>"}, "<file>", "<file>"),872+ ],873+)874+def test_spec_and_help_spec(kwargs, expected_spec, expected_help_spec):875+ """The spec names the argument, while the help spec decorates it with the876+ optionality and repetition markers shown on the help page.877+ """878+ arg = click.Argument(["filename"], **kwargs)879+ ctx = click.Context(click.Command("cli"))880+ assert arg.spec == expected_spec881+ assert arg.get_help_spec(ctx) == expected_help_spec882+883+884+@pytest.mark.parametrize("help_text", [None, "path to the file"])885+def test_help_spec_matches_help_record(help_text):886+ """The help spec is the left column of the argument's help record, whether887+ or not the argument documents itself.888+ """889+ arg = click.Argument(["filename"], help=help_text)890+ ctx = click.Context(click.Command("cli"))891+ assert arg.get_help_spec(ctx) == "FILENAME"892+ assert arg.get_help_record(ctx)[0] == arg.get_help_spec(ctx)893+894+895+@pytest.mark.parametrize(896 ("deprecated", "expected"),897 [(True, "(DEPRECATED)"), ("USE B INSTEAD", "(DEPRECATED: USE B INSTEAD)")],898 )899 @pytest.mark.parametrize("help_text", ["", None])330 unmodified linesmodified:tests/test_deprecations.py+36 added
66 unmodified lines67 with pytest.warns(DeprecationWarning, match="protected_args"):68 assert ctx.protected_args == []69 70 71+@pytest.mark.parametrize(72+ ("param", "expected"),73+ [74+ (click.Option(["-t", "--times"]), "--times"),75+ (click.Argument(["filename"]), "FILENAME"),76+ ],77+ ids=["option", "argument"],78+)79+def test_parameter_human_readable_name_deprecated(param, expected):80+ with pytest.warns(DeprecationWarning, match="human_readable_name"):81+ assert param.human_readable_name == expected82+83+ assert param.spec == expected84+85+86+@pytest.mark.parametrize("base", [click.Parameter, click.Option, click.Argument])87+def test_parameter_human_readable_name_override_deprecated(base):88+ """Click reads ``spec``, so an override of the old property has no effect."""89+ with pytest.warns(DeprecationWarning, match="Override 'spec' instead"):90+91+ class Custom(base): # type: ignore[misc, valid-type]92+ @property93+ def human_readable_name(self) -> str:94+ return "custom"95+96+97+@pytest.mark.parametrize("base", [click.Parameter, click.Option, click.Argument])98+def test_parameter_subclass_without_override_is_silent(base):99+ """The warning names a subclass that overrides the property, and no other."""100+ with warnings.catch_warnings():101+ warnings.simplefilter("error", DeprecationWarning)102+103+ class Custom(base): # type: ignore[misc, valid-type]104+ pass105+106+107 def test_isolated_filesystem_deprecated(runner):108 with pytest.warns(DeprecationWarning, match="isolated_filesystem"):109 with runner.isolated_filesystem():110 pass145 unmodified linesmodified:tests/test_options.py+30 added-1 removed
15 unmodified lines16 import click17 from click import Option18 from click import UNPROCESSED19 from click._utils import UNSET20+from click.parser import _split_opt21 from click.testing import CliRunner22 23 24 def test_prefixes(runner):73 unmodified lines98 else:99 assert opt.get_help_record(ctx)[0] == expected100 101 102+@pytest.mark.parametrize(103+ ("param_decls", "expected_spec", "expected_name"),104+ [105+ (["-t", "--times"], "--times", "times"),106+ (["--times", "-t"], "--times", "times"),107+ (["-t"], "-t", "t"),108+ (["-t", "--times", "--repeat"], "--times", "times"),109+ (["--color/--no-color"], "--color", "color"),110+ (["/debug;/no-debug"], "/debug", "debug"),111+ ],112+)113+def test_spec(param_decls, expected_spec, expected_name):114+ """The spec is the declaration the name was derived from, so the longest115+ prefix wins over declaration order.116+ """117+ opt = click.Option(param_decls)118+ assert opt.spec == expected_spec119+ assert opt.name == expected_name120+ assert _split_opt(opt.spec)[1].replace("-", "_").lower() == opt.name121+122+123+def test_spec_with_explicit_name():124+ """An explicit name declaration leaves the spec to the remaining flags."""125+ opt = click.Option(["--times", "repeat_count"])126+ assert opt.spec == "--times"127+ assert opt.name == "repeat_count"128+129+130 @pytest.mark.parametrize("deprecated", [True, "USE B INSTEAD"])131 def test_deprecated_warning(runner, deprecated):132 @click.command()133 @click.option(8 unmodified lines142 assert "is deprecated" not in result.output143 144 result = runner.invoke(cli, ["--my-option", "hello"])145 assert result.exit_code == 0, result.output117- assert "option 'my_option' is deprecated" in result.output146+ assert "option '--my-option' is deprecated" in result.output147 148 if isinstance(deprecated, str):149 assert deprecated in result.output150 3795 unmodified linesmodified:CHANGES.md+13 added
4 unmodified lines5 - A parameter name that is not a valid Python identifier, or that is a Python6 keyword, is deprecated and raises `TypeError` in Click 9.0. {pr}`3866`7 - An {class}`Option` name written as a Python identifier is deprecated when it8 is not already lower-cased. {pr}`3866`9+- Add {attr}`Parameter.spec`, which returns how the user spells the parameter on10+ the command line: `--times` for an option declared as `-t`, `--times`, and11+ `FILENAME` for an argument declared as `filename`. {pr}`3877`12+- Move {meth}`get_help_spec` from {class}`Option` to {class}`Parameter`, and give13+ {class}`Argument` an override that returns its metavar. {pr}`3877`14+- Error messages and deprecation warnings name an option by its spec instead of15+ its internal name, so they read `The option '--my-option' is deprecated.` where16+ they read `The option 'my_option' is deprecated.` before. {pr}`3877`17+- {attr}`Parameter.human_readable_name` is deprecated and will be removed in18+ Click 9.0. Use {attr}`Parameter.spec` instead. It returned the internal name19+ for options, so its value changes from `my_option` to `--my-option`. Click no20+ longer reads it, and a subclass that overrides it gets a warning when the class21+ is defined. {pr}`3877`22 23 ## Version 8.5.124 25 Unreleased1682 unmodified lines