Skip to content
Myr

Reconcile default value passing and default activation

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

Fix pallets#3111 Reintroduce a commit pushed by mistake in 6c4a77ba24854dab793a8ff72110a0a24c403c9f and reverted in bb7be1f6a91f3fd1267d1a6d68771273d593f9c7 Refine tests introduced in 06847da9126a99c88bf347adf213d33bfe4e4af2 for #3030 Document the interaction between `default` and `flag_value`

authored by Kevin Deldycke · committed by Kevin Deldycke · parent 878de46 · 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

5 files+165 added−15 removed

modified:docs/options.md+92 added-5 removed
339 unmodified lines
340 invoke(info, args=['--lower'])341 invoke(info)342```343344````{note}345The `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` interact345347But 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`.346The `default` value is given to the underlying function347as-is. So if you set `default=None`, the function receives348`None`. Same for any other type.349349Which means, in example above, this option:350But there is a special case for **non-boolean** flags: if a351flag has a non-boolean `flag_value` (like a string or a352class), then `default=True` is interpreted as *the flag353should be activated by default*. The function receives the354`flag_value`, not the Python `True`.355356Which means, in the example above, this option:357358```python359@click.option('--upper', 'transformation', flag_value='upper', default=True)360```361
2 unmodified lines
364```python365@click.option('--upper', 'transformation', flag_value='upper', default='upper')366```367361Because 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.368Because the two are equivalent, it is recommended to always369use the second form and set `default` to the actual value370you want. This makes code more explicit and predictable.371372This 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`.375376The tables below show the value received by the function for377each combination of `default`, `flag_value`, and whether378the flag was passed on the command line.379380#### Boolean flags (`is_flag=True`, boolean `flag_value`)381382These are flags where `flag_value` is `True` or `False`.383The `default` value is always passed through literally384without any special substitution.385386| `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` |398399````{tip}400For a negative flag that defaults to off, prefer the401explicit pair form `--with-xyz/--without-xyz` over the402single-flag `flag_value=False, default=True`:403404```python405@click.option('--with-xyz/--without-xyz', 'enable_xyz', default=True)406```407````408409#### Boolean flag pairs (`--flag/--no-flag`)410411These use secondary option names to provide both an on and412off switch. The `default` value is always literal.413414| `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` |420421#### Non-boolean feature switches (`flag_value` is a string, class, etc.)422423For these flags, `default=True` is a **special case**: it424means "activate this flag by default" and resolves to the425`flag_value`. All other `default` values are passed through426literally.427428| `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"` |434435```{hint}436¹: `default=True` is substituted with `flag_value`.437```438439#### Feature switch groups (multiple flags sharing one variable)440441When multiple `flag_value` options target the same parameter442name, `default=True` on one of them marks it as the default443choice.444445| 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"` |450451## Values from Environment Variables452453To pass in a value from a specific environment variable use `envvar`.454
133 unmodified lines
modified:src/click/core.py+24 added-5 removed
2889 unmodified lines
28902891 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.28992900 For example, with ``--upper/--lower`` feature switches where2901 ``flag_value="upper"`` and ``default=True``, the default resolves2902 to ``"upper"``.29032904 .. 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.29112912 .. 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)29182896 # 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 lines
modified:tests/test_options.py+37 added-2 removed
1455 unmodified lines
1456 ({"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 lines
2487 assert result.exit_code == 0248824892490@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)2505def test_bool_flag_pair_default(runner, default, args, expected):2506 """Boolean flag pairs pass ``default`` through literally.25072508 Ensures ``default=True`` is not replaced by ``flag_value`` for boolean2509 flags, and that ``default=None`` enables 3-state logic.2510 """25112512 @click.command()2513 @click.option("--flag/--no-flag", default=default)2514 def cli(flag):2515 click.echo(repr(flag), nl=False)25162517 result = runner.invoke(cli, args)2518 assert result.exit_code == 02519 assert result.output == repr(expected)252025212522@pytest.mark.parametrize(2523 ("flag_type", "args", "expect_output"),2524 [2525 (str, [], "Default\n"),2526 (str, ["--theflag"], "FlagValue\n"),
36 unmodified lines
modified:tests/test_termui.py+7 added-3 removed
823 unmodified lines
824 # 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 lines
modified:CHANGES.rst+5 added
19 unmodified lines
20- 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`2930Version 8.3.231-------------32
1323 unmodified lines