Support legacy case of default aligning to flag_value for flag whose default=True
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kevin Deldycke · committed by Kevin Deldycke · parent bbe1eb6 · Browse files · 6 files·+148 added−54 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Refs: https://github.com/pallets/click/pull/3030/files#r2288936493
Diff stats
6 files+148 added−54 removed
- tests:+86 added−45 removed
- other:+62 added−9 removed
Provenance
- Commit
06847da- Tree
069328d- Author
Kevin Deldycke <kevin@deldycke.com>- Committer
Kevin Deldycke <kevin@deldycke.com>- Parent
bbe1eb6
6 files changed+148 added−54 removed
modified:docs/options.md+26 added-2 removed
312 unmodified lines313 ```314 315 ## Flag Value316 317-To have an flag pass a value to the underlying function set `flag_value`. This automatically sets `is_flag=True`. To influence the value-less behavior, force its value with `default='upper'`. Setting flag values can be used to create patterns like this:317+To have an flag pass a value to the underlying function set `flag_value`. This automatically sets `is_flag=True`. To mark the flag as default, set `default=True`. Setting flag values can be used to create patterns like this:318 319 ```{eval-rst}320 .. click:example::321 322 import sys323 324 @click.command()325- @click.option('--upper', 'transformation', flag_value='upper', default='upper')325+ @click.option('--upper', 'transformation', flag_value='upper', default=True)326 @click.option('--lower', 'transformation', flag_value='lower')327 def info(transformation):328 click.echo(getattr(sys.platform, transformation)())329 4 unmodified lines334 invoke(info, args=['--lower'])335 invoke(info)336 ```337 338+````{caution}339+The `default` argument of options always [give to the underlying function its value *as-is*](api#click.Parameter).340+341+But for flags, the interaction between `flag_value` and `default` is a bit special.342+343+If a flag has a `flag_value`, setting `default` to `True` means that the flag is activated by default. Not that the value passed to the underlying function is the `True` Python value. Instead, the default value will be aligned to the `flag_value` behind the scenes.344+345+Which means, the in example above, this option:346+347+```python348+@click.option('--upper', 'transformation', flag_value='upper', default=True)349+```350+351+is equivalent to:352+353+```python354+@click.option('--upper', 'transformation', flag_value='upper', default='upper')355+```356+357+This was implemented to support legacy behavior, that will be removed in Click 9.0 to allow for default to take any value, including `True`.358+359+In the mean time, to avoid confusion, it is recommended to always set `default` to the actual default value you want to pass to the underlying function, and not use `True`, `False` or `None`. Unless that's the precise value you want to explicitly force as default.360+````361+362 ## Values from Environment Variables363 364 To pass in a value in from a specific environment variable use `envvar`.365 136 unmodified linesmodified:src/click/core.py+28 added
2593 unmodified lines2594 :param help: the help string.2595 :param hidden: hide this option from help outputs.2596 :param attrs: Other command arguments described in :class:`Parameter`.2597 2598+ .. caution::2599+ Flags specifying a ``flag_value`` and whose ``default=True`` will have2600+ their ``default`` aligned to the ``flag_value``.2601+2602+ This means there is no way to setup a flag whose default ``True`` and2603+ whose ``flag_value`` is something else than ``True``.2604+2605+ This is to support legacy behavior that will be removed in Click 9.0.2606+2607 .. versionchanged:: 8.22608 ``envvar`` used with ``flag_value`` will always use the ``flag_value``,2609 previously it would use the value of the environment variable.2610 119 unmodified lines2730 if self.is_bool_flag:2731 if self.default is UNSET and not self.required:2732 self.default = False2733 2734+ # XXX Support the legacy case of aligning the default value with the flag_value2735+ # for flags whose default is explicitly set to True. As long as we have this2736+ # condition, there is no way a flag can have a default set to True, unless its2737+ # flag_value itself is set to True. Refs:2738+ # https://github.com/pallets/click/issues/3024#issuecomment-31461994612739+ # https://github.com/pallets/click/pull/3030/files#r22889364932740+ if self.default is True and self.flag_value is not UNSET:2741+ # This message is a convoluted way to explain that if you want things2742+ # to be equal, make them equal.2743+ # warnings.warn(2744+ # "A flag's `default` value will no longer be aligned with its "2745+ # "`flag_value` if `default=True` in Click 9.0. If you want the flag to "2746+ # "get the same `default` as its `flag_value`, update the option to "2747+ # "make its `default` parameter equal to its `flag_value`.",2748+ # DeprecationWarning,2749+ # stacklevel=2,2750+ # )2751+ self.default = self.flag_value2752+2753 # Set the default flag_value if it is not set.2754 if self.flag_value is UNSET:2755 if self.is_flag:2756 self.flag_value = True571 unmodified linesmodified:tests/test_basic.py+3 added-1 removed
300 unmodified lines301 (" ᕕ( ᐛ )ᕗ ", [], " ᕕ( ᐛ )ᕗ "),302 (None, [], None),303 # Default is normalized to None if it is UNSET.304 (UNSET, [], None),305+ # Legacy case: if default=True and flag_value is set, The value returned is the306+ # flag_value, not default itself.307+ (True, [], "upper"),308 # Non-string defaults are process as strings by the default Parameter's type.306- (True, [], "True"),309 (False, [], "False"),310 (42, [], "42"),311 (12.3, [], "12.3"),312 ),423 unmodified linesmodified:tests/test_options.py+31 added-11 removed
1295 unmodified lines1296 ({"type": str, "flag_value": None}, ["--foo"], None),1297 # Not passing --foo returns the default value as-is, in its Python type, then1298 # converted by the option type.1299 ({"type": bool, "default": True, "flag_value": True}, [], True),1300- ({"type": bool, "default": True, "flag_value": False}, [], True),1300+ ({"type": bool, "default": True, "flag_value": False}, [], False),1301 ({"type": bool, "default": False, "flag_value": True}, [], False),1302 ({"type": bool, "default": False, "flag_value": False}, [], False),1303 ({"type": bool, "default": None, "flag_value": True}, [], None),1304 ({"type": bool, "default": None, "flag_value": False}, [], None),1305 ({"type": str, "default": True, "flag_value": True}, [], "True"),1306- ({"type": str, "default": True, "flag_value": False}, [], "True"),1306+ ({"type": str, "default": True, "flag_value": False}, [], "False"),1307 ({"type": str, "default": False, "flag_value": True}, [], "False"),1308 ({"type": str, "default": False, "flag_value": False}, [], "False"),1309 ({"type": str, "default": "foo", "flag_value": True}, [], "foo"),1310 ({"type": str, "default": "foo", "flag_value": False}, [], "foo"),77 unmodified lines1388 ("xMl", [], "xMl"),1389 (" ᕕ( ᐛ )ᕗ ", [], " ᕕ( ᐛ )ᕗ "),1390 (None, [], None),1391 (UNSET, [], UNSET),1392+ # Legacy case: if default=True and flag_value is set, The value returned is the1393+ # flag_value, not default itself.1394+ (True, [], "js"),1395 # Non-string defaults are process as strings by the default Parameter's type.1393- (True, [], "True"),1396 (False, [], "False"),1397 (42, [], "42"),1398 (12.3, [], "12.3"),1399 ),507 unmodified lines1907 [],1908 EngineType.OSS,1909 ),1910 # Type is not specified and default to string, so the default value is1909- # returned as a string, even if it is a boolean.1910- ({"flag_value": "1", "default": True}, [], "True"),1911- ({"flag_value": EngineType.OSS, "default": True}, [], "True"),1911+ # returned as a string, even if it is a boolean. Also, defaults to the1912+ # flag_value instead of the default value to support legacy behavior.1913+ ({"flag_value": "1", "default": True}, [], "1"),1914+ ({"flag_value": "1", "default": 42}, [], "42"),1915+ ({"flag_value": EngineType.OSS, "default": True}, [], "EngineType.OSS"),1916+ ({"flag_value": EngineType.OSS, "default": 42}, [], "42"),1917 # See: the result is the same if we force the type to be str.1913- ({"type": str, "flag_value": 1, "default": True}, [], "True"),1914- ({"type": str, "flag_value": "1", "default": True}, [], "True"),1915- ({"type": str, "flag_value": EngineType.OSS, "default": True}, [], "True"),1918+ ({"type": str, "flag_value": 1, "default": True}, [], "1"),1919+ ({"type": str, "flag_value": 1, "default": 42}, [], "42"),1920+ ({"type": str, "flag_value": "1", "default": True}, [], "1"),1921+ ({"type": str, "flag_value": "1", "default": 42}, [], "42"),1922+ (1923+ {"type": str, "flag_value": EngineType.OSS, "default": True},1924+ [],1925+ "EngineType.OSS",1926+ ),1927+ ({"type": str, "flag_value": EngineType.OSS, "default": 42}, [], "42"),1928 # But having the flag value set to integer is automaticcally recognized by Click.1929 ({"flag_value": 1, "default": True}, [], 1),1930+ ({"flag_value": 1, "default": 42}, [], 42),1931 ({"type": int, "flag_value": 1, "default": True}, [], 1),1932+ ({"type": int, "flag_value": 1, "default": 42}, [], 42),1933 ({"type": int, "flag_value": "1", "default": True}, [], 1),1934+ ({"type": int, "flag_value": "1", "default": 42}, [], 42),1935 ],1936 )1937 def test_custom_type_flag_value_standalone_option(runner, opt_params, args, expected):1938 """Test how the type and flag_value influence the returned value.39 unmodified lines1978 EngineType.PRO,1979 ),1980 # Check that passing exotic flag values like classes is supported, but are rendered to strings1981 # when the type is not specified.1967- ({"flag_value": Class1, "default": True}, {"flag_value": Class2}, [], "True"),1982 (1983 {"flag_value": Class1, "default": True},1984 {"flag_value": Class2},1985+ [],1986+ re.compile(r"'<test_options.Class1 object at 0x[0-9A-Fa-f]+>'"),1987+ ),1988+ (1989+ {"flag_value": Class1, "default": True},1990+ {"flag_value": Class2},1991 ["--opt1"],1992 "<class 'test_options.Class1'>",1993 ),1994 (9 unmodified lines2004 (2005 {"flag_value": Class1, "type": UNPROCESSED, "default": True},2006 {"flag_value": Class2, "type": UNPROCESSED},2007 [],1988- True,2008+ re.compile(r"<test_options.Class1 object at 0x[0-9A-Fa-f]+>"),2009 ),2010 (2011 {"flag_value": Class1, "type": UNPROCESSED, "default": True},2012 {"flag_value": Class2, "type": UNPROCESSED},101 unmodified linesmodified:tests/test_termui.py+52 added-33 removed
487 unmodified lines488 result = runner.invoke(cmd, input="my-input", standalone_mode=False)489 assert "my-default-value" not in result.output490 491 492+REPEAT = object()493+"""Sentinel value to indicate that the prompt is expected to be repeated.494+495+I.e. the value provided by the user is not satisfactory and need to be re-prompted.496+"""497+498+INVALID = object()499+"""Sentinel value to indicate that the prompt is expected to be invalid.500+501+On invalid input, Click will output an error message and re-prompt the user.502+"""503+504 BOOLEAN_FLAG_PROMPT_CASES = [505 ###506 ### Test cases with prompt=True explicitly enabled for the flag.507 ###62 unmodified lines570 ### Test cases with prompt=True explicitly enabled for the flag.571 ###572 # Prompt is allowed and the flag has no default, so it prompts.573 # But the flag_value is not set, so it defaults to a string.562- # XXX ({"prompt": True}, [], "", "", ""),574+ ({"prompt": True}, [], "", "", REPEAT),575 ({"prompt": True}, [], "", "y", "y"),576 ({"prompt": True}, [], "", "n", "n"),577 ({"prompt": True}, [], "", "foo", "foo"),578 # This time we provide a boolean flag_value, which makes the flag behave like a4 unmodified lines583 ({"prompt": True, "flag_value": False}, [], "[y/N]", "", False),584 ({"prompt": True, "flag_value": False}, [], "[y/N]", "y", True),585 ({"prompt": True, "flag_value": False}, [], "[y/N]", "n", False),586 # Other flag values changes the auto-detection of the flag type.575- # XXX ({"prompt": True, "flag_value": None}, [], "", "", ""),587+ ({"prompt": True, "flag_value": None}, [], "", "", REPEAT),588 ({"prompt": True, "flag_value": None}, [], "", "y", "y"),589 ({"prompt": True, "flag_value": None}, [], "", "n", "n"),578- # XXX ({"prompt": True, "flag_value": "foo"}, [], "", "", ""),590+ ({"prompt": True, "flag_value": "foo"}, [], "", "", REPEAT),591 ({"prompt": True, "flag_value": "foo"}, [], "", "y", "y"),592 ({"prompt": True, "flag_value": "foo"}, [], "", "n", "n"),593 ###594 ### Test cases with a flag_value and a default.1 unmodified line596 # default=True597 ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "", True),598 ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "y", True),599 ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "n", False),588- ({"prompt": True, "default": True, "flag_value": False}, [], "[Y/n]", "", True),589- ({"prompt": True, "default": True, "flag_value": False}, [], "[Y/n]", "y", True),590- ({"prompt": True, "default": True, "flag_value": False}, [], "[Y/n]", "n", False),600+ ({"prompt": True, "default": True, "flag_value": False}, [], "[y/N]", "", False),601+ ({"prompt": True, "default": True, "flag_value": False}, [], "[y/N]", "y", True),602+ ({"prompt": True, "default": True, "flag_value": False}, [], "[y/N]", "n", False),603 # default=False604 ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "", False),605 ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "y", True),606 ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "n", False),607 ({"prompt": True, "default": False, "flag_value": False}, [], "[y/N]", "", False),608 ({"prompt": True, "default": False, "flag_value": False}, [], "[y/N]", "y", True),609 ({"prompt": True, "default": False, "flag_value": False}, [], "[y/N]", "n", False),610 # default=None599- # XXX600- # (601- # {"prompt": True, "default": None, "flag_value": True},602- # [],603- # "[y/n]",604- # "",605- # False,606- # ),611+ (612+ {"prompt": True, "default": None, "flag_value": True},613+ [],614+ "[y/n]",615+ "",616+ INVALID,617+ ),618 ({"prompt": True, "default": None, "flag_value": True}, [], "[y/n]", "y", True),619 ({"prompt": True, "default": None, "flag_value": True}, [], "[y/n]", "n", False),609- # XXX610- # (611- # {"prompt": True, "default": None, "flag_value": False},612- # [],613- # "[y/n]",614- # "",615- # False,616- # ),620+ (621+ {"prompt": True, "default": None, "flag_value": False},622+ [],623+ "[y/n]",624+ "",625+ INVALID,626+ ),627 ({"prompt": True, "default": None, "flag_value": False}, [], "[y/n]", "y", True),628 ({"prompt": True, "default": None, "flag_value": False}, [], "[y/n]", "n", False),629 # If the flag_value is None, the flag behave like a string flag, whatever the630 # default is.621- ({"prompt": True, "default": True, "flag_value": None}, [], "[True]", "", "True"),622- ({"prompt": True, "default": True, "flag_value": None}, [], "[True]", "y", "y"),623- ({"prompt": True, "default": True, "flag_value": None}, [], "[True]", "n", "n"),631+ ({"prompt": True, "default": True, "flag_value": None}, [], "", "", REPEAT),632+ ({"prompt": True, "default": True, "flag_value": None}, [], "", "y", "y"),633+ ({"prompt": True, "default": True, "flag_value": None}, [], "", "n", "n"),634 (635 {"prompt": True, "default": False, "flag_value": None},636 [],637 "[False]",1 unmodified line639 "False",640 ),641 ({"prompt": True, "default": False, "flag_value": None}, [], "[False]", "y", "y"),642 ({"prompt": True, "default": False, "flag_value": None}, [], "[False]", "n", "n"),633- # XXX ({"prompt": True, "default": None, "flag_value": None}, [], "", "", "False"),643+ ({"prompt": True, "default": None, "flag_value": None}, [], "", "", REPEAT),644 ({"prompt": True, "default": None, "flag_value": None}, [], "", "y", "y"),645 ({"prompt": True, "default": None, "flag_value": None}, [], "", "n", "n"),646 ]647 33 unmodified lines681 682 else:683 expected_output = ""684 if prompt is not None:685+ # Build the expected prompt.686 assert isinstance(prompt, str)676- expected_output += "Flag"677- if prompt:678- expected_output += f" {prompt}"679- expected_output += ": "687+ expected_prompt = f"Flag {prompt}: " if prompt else "Flag: "688+689+ # Add the user input to the expected output.690 assert isinstance(input, str)681- expected_output += f"{input}\n"682- expected_output += f"{expected!r}\n"691+ expected_output += f"{expected_prompt}{input}\n"692 693+ if expected is INVALID:694+ expected_output += "Error: invalid input\n"695+696+ # The prompt is expected to be repeated.697+ if expected in (REPEAT, INVALID):698+ expected_output += expected_prompt699+700+ if expected not in (REPEAT, INVALID):701+ expected_output += f"{expected!r}\n"702+703 assert result.output == expected_output704 assert not result.stderr686- assert result.exit_code == 0705+ assert result.exit_code == 0 if expected not in (REPEAT, INVALID) else 1modified:CHANGES.rst+8 added-7 removed
3 unmodified lines4 -------------5 6 Unreleased7 8-- Rework flag value passing by disentangling use of ``default``. Formerly defaults9- for ``flag_value`` were set by passing ``default=True``, now set by passing10- ``default=<desired_value>``. This change breaks all default settings for flag value11- type flags. In all other places in code, ``default`` takes on the default value.12- Fixing this inconsistency allows the fixing of the linked issues and supports a13- more consistent API. :issue:`1992` :issue:`2012`` :issue:`2514` :issue:`2610`14- :issue:`3024` :pr:`3030`8+- Rework relationship between ``flag_value`` and ``default``: the value given to9+ ``default`` is now left untouched, and keep the value it receive. So10+ ``default=<desired_value>`` is respected and ``<desired_value>`` is passed on as-is11+ to the CLI function. With the exception of flag options, where setting12+ ``default=True`` maintain the legacy behavior of defaulting to the ``flag_value``.13+ This allow ``default`` to be of any type, including ``bool`` or ``None``, fixing14+ inconsistencies reported in: :issue:`1992` :issue:`2012` :issue:`2514`15+ :issue:`2610` :issue:`3024` :pr:`3030`16 - Custom ``callback`` function are now allowed to receive the ``UNSET`` sentinel17 value. :pr:`3030`18 - Allow ``default`` to be set on ``Argument`` for ``nargs = -1``. :issue:`2164`19 :pr:`3030`1268 unmodified lines