Reconcile default value passing and default activation (#3239)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Rowlando13 · committed by GitHub · parents 60cad4a, a683017 · Browse files · 5 files·+165 added−15 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+165 added−15 removed
- tests:+44 added−5 removed
- other:+121 added−10 removed
Provenance
- Commit
8c95c73- Tree
7d46e30- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
60cad4a- Parent 2
a683017
5 files changed+165 added−15 removed
modified:docs/options.md+92 added-5 removed
339 unmodified lines340 invoke(info, args=['--lower'])341 invoke(info)342 ```343 344-````{note}345-The `default` value is given to the decorated function as-is. So if you set `default=None`, the value passed to the function is the `None` Python value. Same for any other type.344+### How `default` and `flag_value` interact345 347-But there is a special case for flags. If a flag has a `flag_value`, then setting `default=True` is interpreted as *the flag should be activated by default*. So instead of the decorated function receiving the `True` Python value, it will receive the `flag_value`.346+The `default` value is given to the underlying function347+as-is. So if you set `default=None`, the function receives348+`None`. Same for any other type.349 349-Which means, in example above, this option:350+But there is a special case for **non-boolean** flags: if a351+flag has a non-boolean `flag_value` (like a string or a352+class), then `default=True` is interpreted as *the flag353+should be activated by default*. The function receives the354+`flag_value`, not the Python `True`.355 356+Which means, in the example above, this option:357+358 ```python359 @click.option('--upper', 'transformation', flag_value='upper', default=True)360 ```361 2 unmodified lines364 ```python365 @click.option('--upper', 'transformation', flag_value='upper', default='upper')366 ```367 361-Because the two are equivalent, it is recommended to always set `default` to the actual value you want to pass and avoid using the special `True` case. This makes the code more explicit and predictable.368+Because the two are equivalent, it is recommended to always369+use the second form and set `default` to the actual value370+you want. This makes code more explicit and predictable.371+372+This special case does **not** apply to boolean flags (where373+`flag_value` is `True` or `False`). For boolean flags,374+`default=True` is the literal Python value `True`.375+376+The tables below show the value received by the function for377+each combination of `default`, `flag_value`, and whether378+the flag was passed on the command line.379+380+#### Boolean flags (`is_flag=True`, boolean `flag_value`)381+382+These are flags where `flag_value` is `True` or `False`.383+The `default` value is always passed through literally384+without any special substitution.385+386+| `default` | `flag_value` | Not passed | `--flag` passed |387+|-----------|--------------|------------|-----------------|388+| *(unset)* | *(unset)* | `False` | `True` |389+| `True` | *(unset)* | `True` | `True` |390+| `False` | *(unset)* | `False` | `True` |391+| `None` | *(unset)* | `None` | `True` |392+| `True` | `True` | `True` | `True` |393+| `True` | `False` | `True` | `False` |394+| `False` | `True` | `False` | `True` |395+| `False` | `False` | `False` | `False` |396+| `None` | `True` | `None` | `True` |397+| `None` | `False` | `None` | `False` |398+399+````{tip}400+For a negative flag that defaults to off, prefer the401+explicit pair form `--with-xyz/--without-xyz` over the402+single-flag `flag_value=False, default=True`:403+404+```python405+@click.option('--with-xyz/--without-xyz', 'enable_xyz', default=True)406+```407 ````408 409+#### Boolean flag pairs (`--flag/--no-flag`)410+411+These use secondary option names to provide both an on and412+off switch. The `default` value is always literal.413+414+| `default` | Not passed | `--flag` | `--no-flag` |415+|-----------|------------|----------|-------------|416+| *(unset)* | `False` | `True` | `False` |417+| `True` | `True` | `True` | `False` |418+| `False` | `False` | `True` | `False` |419+| `None` | `None` | `True` | `False` |420+421+#### Non-boolean feature switches (`flag_value` is a string, class, etc.)422+423+For these flags, `default=True` is a **special case**: it424+means "activate this flag by default" and resolves to the425+`flag_value`. All other `default` values are passed through426+literally.427+428+| `default` | `flag_value` | Not passed | `--flag` passed |429+|------------|--------------|-------------|-----------------|430+| *(unset)* | `"upper"` | `None` | `"upper"` |431+| `True` | `"upper"` | `"upper"`¹ | `"upper"` |432+| `"lower"` | `"upper"` | `"lower"` | `"upper"` |433+| `None` | `"upper"` | `None` | `"upper"` |434+435+```{hint}436+¹: `default=True` is substituted with `flag_value`.437+```438+439+#### Feature switch groups (multiple flags sharing one variable)440+441+When multiple `flag_value` options target the same parameter442+name, `default=True` on one of them marks it as the default443+choice.444+445+| Definition | Not passed | `--upper` | `--lower` |446+|--------------------------------------------------------|------------|-----------|-----------|447+| `--upper` with `flag_value='upper'`, `default=True` | `"upper"` | `"upper"` | `"lower"` |448+| `--upper` with `flag_value='upper'`, `default='upper'` | `"upper"` | `"upper"` | `"lower"` |449+| Both without `default` | `None` | `"upper"` | `"lower"` |450+451 ## Values from Environment Variables452 453 To pass in a value from a specific environment variable use `envvar`.454 133 unmodified linesmodified:src/click/core.py+24 added-5 removed
2889 unmodified lines2890 2891 def get_default(2892 self, ctx: Context, call: bool = True2893 ) -> t.Any | t.Callable[[], t.Any] | None:2894+ """For non-boolean flag options, ``default=True`` is treated as a2895+ sentinel meaning "activate this flag by default" and is resolved to2896+ :attr:`flag_value`. This resolution is performed lazily here (rather2897+ than eagerly in :meth:`__init__`) to prevent callable ``flag_value``2898+ values (like classes) from being instantiated prematurely.2899+2900+ For example, with ``--upper/--lower`` feature switches where2901+ ``flag_value="upper"`` and ``default=True``, the default resolves2902+ to ``"upper"``.2903+2904+ .. caution::2905+ This substitution only applies to **non-boolean** flags2906+ (:attr:`is_bool_flag` is ``False``). For boolean flags, ``True`` is2907+ not a sentinel but a legitimate Python value, so ``default=True`` is2908+ returned as-is. Without this distinction, ``flag_value=False,2909+ default=True`` would silently always return ``False``, regardless of2910+ whether the flag was passed or not.2911+2912+ .. versionchanged:: 8.3.32913+ ``default=True`` is no longer substituted with ``flag_value`` for2914+ boolean flags, fixing negative boolean flags like ``flag_value=False,2915+ default=True``.2916+ """2917 value = super().get_default(ctx, call=False)2918 2896- # Lazily resolve default=True to flag_value. Doing this here2897- # (instead of eagerly in __init__) prevents callable flag_values2898- # (like classes) from being instantiated by the callable check below.2899- # https://github.com/pallets/click/issues/31212900- if value is True and self.is_flag:2919+ if value is True and self.is_flag and not self.is_bool_flag:2920 value = self.flag_value2921 elif call and callable(value):2922 value = value()2923 533 unmodified linesmodified:tests/test_options.py+37 added-2 removed
1455 unmodified lines1456 ({"type": str, "flag_value": "foo"}, ["--foo"], "foo"),1457 ({"type": str, "flag_value": None}, [], None),1458 ({"type": str, "flag_value": None}, ["--foo"], None),1459 # Not passing --foo returns the default value as-is, in its Python type, then1460- # converted by the option type.1460+ # converted by the option type. For boolean flags, default=True is a literal1461+ # value, not a sentinel meaning "activate flag". So it is NOT substituted with1462+ # flag_value. See: https://github.com/pallets/click/issues/31111463+ # https://github.com/pallets/click/pull/32391464 ({"type": bool, "default": True, "flag_value": True}, [], True),1462- ({"type": bool, "default": True, "flag_value": False}, [], False),1465+ ({"type": bool, "default": True, "flag_value": False}, [], True),1466 ({"type": bool, "default": False, "flag_value": True}, [], False),1467 ({"type": bool, "default": False, "flag_value": False}, [], False),1468 ({"type": bool, "default": None, "flag_value": True}, [], None),1469 ({"type": bool, "default": None, "flag_value": False}, [], None),1017 unmodified lines2487 assert result.exit_code == 02488 2489 2490 @pytest.mark.parametrize(2491+ ("default", "args", "expected"),2492+ [2493+ # default=None: 3-state pattern (e.g. Flask --reload/--no-reload).2494+ # https://github.com/pallets/click/issues/30242495+ (None, [], None),2496+ (None, ["--flag"], True),2497+ (None, ["--no-flag"], False),2498+ # default=True: literal value, not substituted with flag_value.2499+ # https://github.com/pallets/click/issues/31112500+ (True, [], True),2501+ (True, ["--flag"], True),2502+ (True, ["--no-flag"], False),2503+ ],2504+)2505+def test_bool_flag_pair_default(runner, default, args, expected):2506+ """Boolean flag pairs pass ``default`` through literally.2507+2508+ Ensures ``default=True`` is not replaced by ``flag_value`` for boolean2509+ flags, and that ``default=None`` enables 3-state logic.2510+ """2511+2512+ @click.command()2513+ @click.option("--flag/--no-flag", default=default)2514+ def cli(flag):2515+ click.echo(repr(flag), nl=False)2516+2517+ result = runner.invoke(cli, args)2518+ assert result.exit_code == 02519+ assert result.output == repr(expected)2520+2521+2522+@pytest.mark.parametrize(2523 ("flag_type", "args", "expect_output"),2524 [2525 (str, [], "Default\n"),2526 (str, ["--theflag"], "FlagValue\n"),36 unmodified linesmodified:tests/test_termui.py+7 added-3 removed
823 unmodified lines824 # default=True825 ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "", True),826 ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "y", True),827 ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "n", False),828+ # For boolean flags, default=True is a literal value, not a sentinel meaning829+ # "activate flag", so the prompt shows [Y/n] with default=True. See:830+ # https://github.com/pallets/click/issues/3111831+ # https://github.com/pallets/click/pull/3239828- ({"prompt": True, "default": True, "flag_value": False}, [], "[y/N]", "", False),829- ({"prompt": True, "default": True, "flag_value": False}, [], "[y/N]", "y", True),830- ({"prompt": True, "default": True, "flag_value": False}, [], "[y/N]", "n", False),832+ ({"prompt": True, "default": True, "flag_value": False}, [], "[Y/n]", "", True),833+ ({"prompt": True, "default": True, "flag_value": False}, [], "[Y/n]", "y", True),834+ ({"prompt": True, "default": True, "flag_value": False}, [], "[Y/n]", "n", False),835 # default=False836 ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "", False),837 ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "y", True),838 ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "n", False),99 unmodified linesmodified:CHANGES.rst+5 added
19 unmodified lines20 - Add optional randomized parallel test execution using ``pytest-randomly`` and21 ``pytest-xdist`` to detect test pollution and race conditions. :pr:`3151`22 - Add contributor documentation for running stress tests, randomized23 parallel tests, and Flask smoke tests. :pr:`3151` :pr:`3177`24+- Fix ``default=True`` with boolean ``flag_value`` always returning the25+ ``flag_value`` instead of ``True``. The ``default=True`` to ``flag_value``26+ substitution now only applies to non-boolean flags, where ``True`` acts as a27+ sentinel meaning "activate this flag by default". For boolean flags,28+ ``default=True`` is returned as a literal value. :issue:`3111` :pr:`3239`29 - Mark ``make_default_short_help`` as private API. :issue:`3189` :pr:`3250`30 - ``CliRunner``'s redirected streams now expose the original file descriptor31 via ``fileno()``, so that ``faulthandler``, ``subprocess``, and other32 C-level consumers no longer crash with ``io.UnsupportedOperation``.1328 unmodified lines