Skip to content
Myr

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
This landing

State

Landed as 2247b35

By oscabriel

Diff stats

7 files+266 added−26 removed

  • tests:+96 added−1 removed
  • other:+170 added−25 removed

7 files+266 added−26 removed

modified:docs/parameters.md+34 added-12 removed
modified:docs/upgrade-guides.md+2 added-1 removed
14 unmodified lines
15For 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.2021### Removals with prior deprecation2223For 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 lines
29- TBD3031### Changes3232- 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.3435### Fixes3637- TBD
modified:src/click/core.py+121 added-12 removed
103 unmodified lines
104 """Write the final abort message to standard error."""105 echo(_("Aborted!"), file=sys.stderr)106107108def _outside_click_stacklevel() -> int:108def _outside_click_stacklevel(skip: cabc.Container[str] = ()) -> int:109 """Depth of the first stack frame outside Click.110111 :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.114115 .. versionadded:: 8.6.0116 """117 frame: FrameType | None = sys._getframe(1)118 level = 1119120 while frame is not None:121 module = frame.f_globals.get("__name__", "")122119 if module != "click" and not module.startswith("click."):123 if module != "click" and not module.startswith("click.") and module not in skip:124 return level125126 frame = frame.f_back127 level += 1
2117 unmodified lines
2245 intentionally not finalized.22462247 Some settings are supported by both options and arguments.22482249 Three distinct strings designate a parameter, each with its own audience:22502251 ``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`.22592260 :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 lines
23482349 param_type_name = "parameter"23502351 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.23612362 For an :class:`Option` these are the prefixed declarations the parser2363 matches, in declaration order: ``["-t", "--times"]``. :attr:`spec` is the2364 canonical one.23652366 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: int
9 unmodified lines
2388 )2389 deprecated: bool | str2390 help: str | None23912392 def __init_subclass__(cls, **kwargs: t.Any) -> None:2393 super().__init_subclass__(**kwargs)23942395 if "human_readable_name" in cls.__dict__:2396 import warnings23972398 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 )24052406 def __init__(2407 self,2408 param_decls: cabc.Sequence[str] | None = None,2409 type: types.ParamType[t.Any] | t.Any | None = None,
71 unmodified lines
2481 )24822483 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 lines
2566 stacklevel=_outside_click_stacklevel(),2567 )25682569 @property2570 def spec(self) -> str:2571 """Returns how the user spells this parameter on the command line.25722573 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`.25772578 .. versionadded:: 8.6.02579 """2580 if not self.opts:2581 return self.name25822583 return max(self.opts, key=lambda opt: len(_split_opt(opt)[0]))25842585 @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.25882589 .. 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 warnings25962597 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.spec26042605 def get_help_spec(self, ctx: Context) -> str:2606 """Returns the left column of this parameter's help record.26072608 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.26122613 Unlike ``get_help_record()``, the spec is produced even when the2614 parameter is left out of the help page, like a hidden option.26152616 .. versionadded:: 8.6.02617 """2618 return self.spec26192620 def make_metavar(self, ctx: Context) -> str:2621 if self.metavar is not None:2622 return self.metavar2623
342 unmodified lines
2966 "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 lines
30263027 .. 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)30323033 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]:3034 """Return a list of completions for the incomplete value. If a
893 unmodified lines
39283929 super().__init__(param_decls, required=required, help=help, **attrs)39303931 @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.39373938 .. versionadded:: 8.6.03939 """3940 if self.metavar is not None:3941 return self.metavar3942 return self.name.upper()3943
39 unmodified lines
39833984 def get_usage_pieces(self, ctx: Context) -> list[str]:3985 return [self.make_metavar(ctx)]39863987 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]``.39903991 .. versionadded:: 8.6.03992 """3993 return self.make_metavar(ctx)39943995 def get_help_record(self, ctx: Context) -> tuple[str, str]:3996 """Returns the argument's help row: its metavar and its help text.39973998 Unlike :meth:`Option.get_help_record`, this never returns ``None``. An
3 unmodified lines
4002 .. 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 ""40074008 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}'"40124013 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 lines
modified:tests/test_arguments.py+30 added
861 unmodified lines
862 assert "(DEPRECATED)" in result.output863864865@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)874def 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_spec882883884@pytest.mark.parametrize("help_text", [None, "path to the file"])885def 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)893894895@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 lines
modified:tests/test_deprecations.py+36 added
66 unmodified lines
67 with pytest.warns(DeprecationWarning, match="protected_args"):68 assert ctx.protected_args == []697071@pytest.mark.parametrize(72 ("param", "expected"),73 [74 (click.Option(["-t", "--times"]), "--times"),75 (click.Argument(["filename"]), "FILENAME"),76 ],77 ids=["option", "argument"],78)79def test_parameter_human_readable_name_deprecated(param, expected):80 with pytest.warns(DeprecationWarning, match="human_readable_name"):81 assert param.human_readable_name == expected8283 assert param.spec == expected848586@pytest.mark.parametrize("base", [click.Parameter, click.Option, click.Argument])87def 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"):9091 class Custom(base): # type: ignore[misc, valid-type]92 @property93 def human_readable_name(self) -> str:94 return "custom"959697@pytest.mark.parametrize("base", [click.Parameter, click.Option, click.Argument])98def 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)102103 class Custom(base): # type: ignore[misc, valid-type]104 pass105106107def test_isolated_filesystem_deprecated(runner):108 with pytest.warns(DeprecationWarning, match="isolated_filesystem"):109 with runner.isolated_filesystem():110 pass
145 unmodified lines
modified:tests/test_options.py+30 added-1 removed
15 unmodified lines
16import click17from click import Option18from click import UNPROCESSED19from click._utils import UNSET20from click.parser import _split_opt21from click.testing import CliRunner222324def test_prefixes(runner):
73 unmodified lines
98 else:99 assert opt.get_help_record(ctx)[0] == expected100101102@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)113def 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.name121122123def 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"128129130@pytest.mark.parametrize("deprecated", [True, "USE B INSTEAD"])131def test_deprecated_warning(runner, deprecated):132 @click.command()133 @click.option(
8 unmodified lines
142 assert "is deprecated" not in result.output143144 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.output147148 if isinstance(deprecated, str):149 assert deprecated in result.output150
3795 unmodified lines
modified:CHANGES.md+13 added
4 unmodified lines
5- 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`2223## Version 8.5.12425Unreleased
1682 unmodified lines