Skip to content
Myr

Fix dual-option arbitration to respect explicit defaults

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

Closes #3403

authored by Kevin Deldycke · committed by Kevin Deldycke · parent c943271 · Browse files · 4 files+991 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

4 files+991 added−15 removed

  • tests:+817 added−0 removed
  • other:+174 added−15 removed

4 files+991 added−15 removed

modified:docs/options.md+120 added-4 removed
467 unmodified lines
468```469470#### Feature switch groups (multiple flags sharing one variable)471472When multiple `flag_value` options target the same parameter473name, `default=True` on one of them marks it as the default474choice.472Several `flag_value` options can target the same parameter name to form a473feature switch group. The user picks one flag on the command line, and the474function receives the corresponding `flag_value`. When the user picks none,475Click falls back to whichever option claims the slot under the arbitration476rules described below.477478##### Non-boolean groups479480For non-boolean `flag_value` (strings, enum members, classes, ...), place481`default=True` on the option that should win when no flag is passed. The482substitution rule above resolves it to that option's `flag_value`. Any other483explicit `default` is passed through literally.484485| Definition | Not passed | `--upper` | `--lower` |486|--------------------------------------------------------|------------|-----------|-----------|487| `--upper` with `flag_value='upper'`, `default=True` | `"upper"` | `"upper"` | `"lower"` |488| `--upper` with `flag_value='upper'`, `default='upper'` | `"upper"` | `"upper"` | `"lower"` |480| Both without `default` | `None` | `"upper"` | `"lower"` |489| `--upper` with `flag_value='upper'`, `default=None` | `None` | `"upper"` | `"lower"` |490| Neither option carries a `default` | `None` | `"upper"` | `"lower"` |491492The third row is the three-state pattern: the function receives `None` when no493flag is passed, distinguishable from either explicit choice.494495##### Boolean groups496497When `flag_value` is `True` or `False`, the substitution rule does not apply:498`default=True` is the literal Python `True`. To make one flag in an499enable/disable pair the default, set its `default=True` explicitly:500501```python502@click.option("--without-xyz", "enable_xyz", flag_value=False)503@click.option("--with-xyz", "enable_xyz", flag_value=True, default=True)504```505506| Definition | Not passed | `--with-xyz` | `--without-xyz` |507|---------------------------------------------------------|------------|--------------|-----------------|508| `--with-xyz` with `flag_value=True`, `default=True` | `True` | `True` | `False` |509| `--without-xyz` with `flag_value=False`, `default=False`| `False` | `True` | `False` |510| `--with-xyz` with `flag_value=True`, `default=None` | `None` | `True` | `False` |511| Neither option carries a `default` | `False` | `True` | `False` |512513```{tip}514For most enable/disable cases, the pair form `--with-xyz/--without-xyz` is515shorter and equivalent. The multi-flag group form is useful when the on and off516flags need distinct names without a shared stem, or when each flag needs its517own help text.518```519520##### Arbitration rules521522When several options in a group resolve their values simultaneously, only one523wins the parameter slot. The full arbitration policy (source precedence,524explicit-beats-auto tie-break, first-declared fallback) is enumerated under525[Option value resolution](#option-value-resolution).526527## Option value resolution528529This section enumerates the rules Click applies when computing the value530delivered to the decorated function for every option. Rules are listed in the531order they fire during the parsing pipeline.532533### Type inference534535Without an explicit `type=`, Click infers the parameter type at construction:5365371. If `flag_value` is `True` or `False`, the type is {class}`BoolParamType`.5382. If `flag_value` is an `int`, `float`, or `str`, the type is the matching539 basic type.5403. If `flag_value` is any other Python object (a class, an enum member, a541 `frozenset`, ...), the type is {data}`UNPROCESSED` so the value passes542 through unchanged.5434. Otherwise, the type is inferred from `default` if set, falling back to544 {class}`StringParamType` when neither hint is available.545546### `default` interpretation547548The literal value passed as `default=` is interpreted differently depending on549whether the option is a flag and what `flag_value` it carries:5505511. `default=UNSET` (the absence sentinel) is treated as if `default` was not552 passed at all. It does not count as "the user picked nothing", and it does553 not count as an explicit default for arbitration purposes.5542. For a bare boolean flag (no `flag_value`, or `flag_value` of `True` or555 `False`), an unset `default` auto-derives to `False`.5563. For a non-boolean flag with a `flag_value`, `default=True` is substituted557 with `flag_value`. This is the "activate this flag by default" shorthand.558 Any non-`True` `default` is passed through literally.5594. For a boolean flag with `flag_value` set, `default=True` is the literal560 Python `True`. The substitution from rule 3 does not apply.5615. `default=None` is always a real explicit value, distinct from `UNSET`562 absence.5636. Any other `default` is delivered to the function unchanged after conversion564 through the parameter's type.565566### Value sources567568Click resolves the value of every option from the following569sources, in order of decreasing precedence:5705711. **command line input** ({attr}`ParameterSource.COMMANDLINE`),5722. **environment variable** named in `envvar=` or derived from `auto_envvar_prefix`573 ({attr}`ParameterSource.ENVIRONMENT`),5743. **`default_map` entry** matching the parameter name on the active {class}`Context`575 ({attr}`ParameterSource.DEFAULT_MAP`),5764. **parameter default** ({attr}`ParameterSource.DEFAULT`).577578The first source that produces a value wins. Environment variables and579`default_map` entries set to `Sentinel.UNSET` are skipped, so they fall through580to the next source rather than supplying `UNSET` to the function.581582### Slot arbitration583584Several options can target the same `name` to form a feature switch group. When585they do, only one option's value reaches the function. Arbitration applies586these rules, in order:5875881. **By source.** Whichever option resolved its value from the most explicit589 source wins, regardless of decorator order. Any command-line input beats any590 default, an environment variable beats a `default_map` entry, and so on.5912. **Within the default tier, explicit beats auto-derived.** An option that592 received an explicit `default=` keyword wins over one whose default came593 from `default` interpretation.5943. **Otherwise, last declared wins.** When all options in the group resolved595 from the same source and tier (all auto-derived defaults, or all explicit596 defaults), the option declared last in the source code keeps the slot.597598## Values from Environment Variables599600To pass in a value from a specific environment variable use `envvar`.601
151 unmodified lines
modified:src/click/core.py+46 added-11 removed
452 unmodified lines
453454 self._close_callbacks: list[t.Callable[[], t.Any]] = []455 self._depth = 0456 self._parameter_source: dict[str, ParameterSource] = {}457 # Tracks whether the option that currently owns each parameter slot in458 # :attr:`params` had its ``default`` set explicitly by the user. Used459 # to tie-break feature-switch groups where multiple options share a460 # parameter name and both fall back to their default value.461 # Refs: https://github.com/pallets/click/issues/3403462 self._param_default_explicit: dict[str, bool] = {}463 self._exit_stack = ExitStack()464465 @property466 def protected_args(self) -> list[str]:
1733 unmodified lines
2200 self.nargs = nargs2201 self.multiple = multiple2202 self.expose_value = expose_value2203 self.default: t.Any | t.Callable[[], t.Any] | None = default2204 # Whether the user passed ``default`` explicitly to the constructor.2205 # Captured before any auto-derived default (like ``False`` for boolean2206 # flags in :class:`Option`) replaces the :data:`UNSET` sentinel, so it2207 # remains ``False`` when the default was inferred rather than chosen.2208 # Refs: https://github.com/pallets/click/issues/34032209 self._default_explicit: bool = default is not UNSET2210 self.is_eager = is_eager2211 self.metavar = metavar2212 self.envvar = envvar2213 self._custom_shell_complete = shell_complete
378 unmodified lines
2592 a default).25932594 :meta private:2595 """2596 # Capture the slot's existing state before we mutate2597 # ``_parameter_source`` so the write decision below can compare our2598 # incoming source against the source of the option that already wrote2599 # the slot (if any).2600 existing_value = ctx.params.get(self.name, UNSET)2601 existing_source = ctx.get_parameter_source(self.name)2602 existing_default_explicit = ctx._param_default_explicit.get(self.name, False)26032604 with augment_usage_errors(ctx, param=self):2605 value, source = self.consume_value(ctx, opts)26062587 ctx.set_parameter_source(self.name, source)25882607 # Display a deprecation warning if necessary.2608 if (2609 self.deprecated2610 and value is not UNSET
22 unmodified lines
2633 # value is incompatible with the parameter type, so we reset the value2634 # to UNSET, which will be interpreted as a missing value.2635 value = UNSET26362619 # Add parameter's value to the context.2620 if (2621 self.expose_value2622 # We skip adding the value if it was previously set by another parameter2623 # targeting the same variable name. This prevents parameters competing for2624 # the same name to override each other.2625 and (self.name not in ctx.params or ctx.params[self.name] is UNSET)2626 ):2627 ctx.params[self.name] = value2637 # Arbitrate the slot when several parameters target the same variable2638 # name (feature-switch groups). See: https://github.com/pallets/click/issues/34032639 slot_empty = existing_value is UNSET2640 more_explicit = existing_source is not None and source < existing_source2641 same_source = existing_source is not None and source == existing_source2642 auto_would_downgrade_explicit = (2643 same_source2644 and source == ParameterSource.DEFAULT2645 and existing_default_explicit2646 and not self._default_explicit2647 )2648 is_winner = (2649 slot_empty2650 or more_explicit2651 or (same_source and not auto_would_downgrade_explicit)2652 )26532654 if is_winner:2655 ctx.set_parameter_source(self.name, source)2656 if self.expose_value:2657 ctx.params[self.name] = value2658 ctx._param_default_explicit[self.name] = self._default_explicit2659 elif existing_source is None:2660 # Nothing has claimed the slot yet. Record at least our source so downstream2661 # lookups don't return ``None``.2662 ctx.set_parameter_source(self.name, source)26632664 return value, args26652666 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:2667 return None
870 unmodified lines
modified:tests/test_options.py+817 added
2580 unmodified lines
2581 assert result.output == repr(expected)258225832584@pytest.mark.parametrize(2585 ("opts", "args", "expected"),2586 [2587 # #3403 reproducer: enable/disable pair with explicit ``default=True``2588 # on the positive flag, declared after (inner decorator) the negative.2589 # https://github.com/pallets/click/issues/34032590 pytest.param(2591 [2592 ("--without-xyz", {"flag_value": False}),2593 ("--with-xyz", {"flag_value": True, "default": True}),2594 ],2595 [],2596 True,2597 id="3403-reproducer-no-args",2598 ),2599 pytest.param(2600 [2601 ("--without-xyz", {"flag_value": False}),2602 ("--with-xyz", {"flag_value": True, "default": True}),2603 ],2604 ["--with-xyz"],2605 True,2606 id="3403-reproducer-with-only",2607 ),2608 pytest.param(2609 [2610 ("--without-xyz", {"flag_value": False}),2611 ("--with-xyz", {"flag_value": True, "default": True}),2612 ],2613 ["--without-xyz"],2614 False,2615 id="3403-reproducer-without-only",2616 ),2617 # When both flags are passed, the parser keeps the last value seen.2618 pytest.param(2619 [2620 ("--without-xyz", {"flag_value": False}),2621 ("--with-xyz", {"flag_value": True, "default": True}),2622 ],2623 ["--with-xyz", "--without-xyz"],2624 False,2625 id="3403-reproducer-with-then-without",2626 ),2627 pytest.param(2628 [2629 ("--without-xyz", {"flag_value": False}),2630 ("--with-xyz", {"flag_value": True, "default": True}),2631 ],2632 ["--without-xyz", "--with-xyz"],2633 True,2634 id="3403-reproducer-without-then-with",2635 ),2636 # Order-independence: explicit ``default=True`` on the OUTER2637 # decorator (declared first) must produce the same behavior.2638 pytest.param(2639 [2640 ("--with-xyz", {"flag_value": True, "default": True}),2641 ("--without-xyz", {"flag_value": False}),2642 ],2643 [],2644 True,2645 id="explicit-default-outer-no-args",2646 ),2647 pytest.param(2648 [2649 ("--with-xyz", {"flag_value": True, "default": True}),2650 ("--without-xyz", {"flag_value": False}),2651 ],2652 ["--without-xyz"],2653 False,2654 id="explicit-default-outer-cmdline-overrides",2655 ),2656 # Explicit ``default=False`` on the negative flag wins over the2657 # auto-derived default of the positive one. Result value is False2658 # either way, but the assertion still guards source tracking.2659 pytest.param(2660 [2661 ("--with-xyz", {"flag_value": True}),2662 ("--without-xyz", {"flag_value": False, "default": False}),2663 ],2664 [],2665 False,2666 id="explicit-default-false-on-negative",2667 ),2668 # Explicit ``default=True`` on the negative flag is unusual but2669 # legal: post-#3239, it is a literal Python value, not a sentinel.2670 pytest.param(2671 [2672 ("--with-xyz", {"flag_value": True}),2673 ("--without-xyz", {"flag_value": False, "default": True}),2674 ],2675 [],2676 True,2677 id="explicit-default-true-on-negative",2678 ),2679 # Both options carry an explicit default: last-wins, so the option2680 # declared last in the source code keeps the slot. Confirms the2681 # explicit-beats-auto tie-break does not also promote first-declared2682 # over a later explicit default.2683 pytest.param(2684 [2685 ("--with-xyz", {"flag_value": True, "default": True}),2686 ("--without-xyz", {"flag_value": False, "default": False}),2687 ],2688 [],2689 False,2690 id="both-explicit-defaults-last-wins",2691 ),2692 pytest.param(2693 [2694 ("--without-xyz", {"flag_value": False, "default": False}),2695 ("--with-xyz", {"flag_value": True, "default": True}),2696 ],2697 [],2698 True,2699 id="both-explicit-defaults-last-wins-swapped",2700 ),2701 # No option has an explicit default: every boolean flag2702 # auto-derives ``default=False`` regardless of its ``flag_value``,2703 # so the slot is False either way. Last-wins applies under the hood2704 # but is not observable because both values are equal.2705 pytest.param(2706 [2707 ("--with-xyz", {"flag_value": True}),2708 ("--without-xyz", {"flag_value": False}),2709 ],2710 [],2711 False,2712 id="both-auto-defaults-positive-first",2713 ),2714 pytest.param(2715 [2716 ("--without-xyz", {"flag_value": False}),2717 ("--with-xyz", {"flag_value": True}),2718 ],2719 [],2720 False,2721 id="both-auto-defaults-negative-first",2722 ),2723 # Explicit ``default=False`` matching the auto-derived value:2724 # the explicit option still wins the slot. Confirms tracking is2725 # source-based and not value-based.2726 pytest.param(2727 [2728 ("--with-xyz", {"flag_value": True, "default": False}),2729 ("--without-xyz", {"flag_value": False}),2730 ],2731 [],2732 False,2733 id="explicit-default-matches-auto-still-wins",2734 ),2735 # Three-flag group: the explicit default wins regardless of its2736 # position in the decorator stack.2737 pytest.param(2738 [2739 ("--auto-a", {"flag_value": True}),2740 ("--explicit", {"flag_value": False, "default": False}),2741 ("--auto-b", {"flag_value": True}),2742 ],2743 [],2744 False,2745 id="three-flags-explicit-in-middle",2746 ),2747 pytest.param(2748 [2749 ("--auto-a", {"flag_value": True}),2750 ("--auto-b", {"flag_value": False}),2751 ("--explicit", {"flag_value": True, "default": True}),2752 ],2753 [],2754 True,2755 id="three-flags-explicit-last",2756 ),2757 pytest.param(2758 [2759 ("--explicit", {"flag_value": False, "default": False}),2760 ("--auto-a", {"flag_value": True}),2761 ("--auto-b", {"flag_value": True}),2762 ],2763 [],2764 False,2765 id="three-flags-explicit-first",2766 ),2767 # Three-state pattern: explicit ``default=None`` on one option2768 # must beat a sibling's auto-derived ``False``.2769 pytest.param(2770 [2771 ("--without-xyz", {"flag_value": False}),2772 ("--with-xyz", {"flag_value": True, "default": None}),2773 ],2774 [],2775 None,2776 id="explicit-default-none-three-state",2777 ),2778 pytest.param(2779 [2780 ("--without-xyz", {"flag_value": False}),2781 ("--with-xyz", {"flag_value": True, "default": None}),2782 ],2783 ["--with-xyz"],2784 True,2785 id="explicit-default-none-three-state-with",2786 ),2787 pytest.param(2788 [2789 ("--without-xyz", {"flag_value": False}),2790 ("--with-xyz", {"flag_value": True, "default": None}),2791 ],2792 ["--without-xyz"],2793 False,2794 id="explicit-default-none-three-state-without",2795 ),2796 # Command-line input always beats any default, regardless of2797 # which option carried the explicit default.2798 pytest.param(2799 [2800 ("--with-xyz", {"flag_value": True, "default": True}),2801 ("--without-xyz", {"flag_value": False}),2802 ],2803 ["--without-xyz"],2804 False,2805 id="cmdline-beats-explicit-default",2806 ),2807 pytest.param(2808 [2809 ("--without-xyz", {"flag_value": False, "default": False}),2810 ("--with-xyz", {"flag_value": True}),2811 ],2812 ["--with-xyz"],2813 True,2814 id="cmdline-beats-explicit-default-symmetric",2815 ),2816 ],2817)2818def test_bool_flag_group_competition(runner, opts, args, expected):2819 """Competing boolean flags sharing a single parameter name.28202821 Verifies the arbitration rules between options that target the same2822 variable name in a feature-switch group.28232824 Regression test for https://github.com/pallets/click/issues/34032825 """28262827 @click.command()2828 def cli(enable_xyz):2829 click.echo(repr(enable_xyz), nl=False)28302831 for opt_name, opt_kwargs in opts:2832 cli = click.option(opt_name, "enable_xyz", **opt_kwargs)(cli)28332834 result = runner.invoke(cli, args)2835 assert result.exit_code == 0, result.output2836 assert result.output == repr(expected)283728382839@pytest.mark.parametrize(2840 ("envvar_value", "args", "expected"),2841 [2842 # An env var on one option in the group provides ENVIRONMENT source,2843 # which beats any sibling's DEFAULT regardless of explicit-default.2844 ("1", [], True),2845 ("0", [], False),2846 # Command-line still beats the env var.2847 ("0", ["--with-xyz"], True),2848 ("1", ["--without-xyz"], False),2849 ],2850)2851def test_bool_flag_group_competition_with_envvar(2852 runner, monkeypatch, envvar_value, args, expected2853):2854 monkeypatch.setenv("XYZ", envvar_value)28552856 @click.command()2857 @click.option("--without-xyz", "enable_xyz", flag_value=False)2858 @click.option(2859 "--with-xyz",2860 "enable_xyz",2861 flag_value=True,2862 default=False,2863 envvar="XYZ",2864 )2865 def cli(enable_xyz):2866 click.echo(repr(enable_xyz), nl=False)28672868 result = runner.invoke(cli, args)2869 assert result.exit_code == 0, result.output2870 assert result.output == repr(expected)287128722873@pytest.mark.parametrize(2874 ("default_map", "args", "expected"),2875 [2876 # ``default_map`` provides DEFAULT_MAP source, beating either default.2877 ({"enable_xyz": True}, [], True),2878 ({"enable_xyz": False}, [], False),2879 # Command-line still beats default_map.2880 ({"enable_xyz": False}, ["--with-xyz"], True),2881 ({"enable_xyz": True}, ["--without-xyz"], False),2882 ],2883)2884def test_bool_flag_group_competition_with_default_map(2885 runner, default_map, args, expected2886):2887 @click.command()2888 @click.option("--without-xyz", "enable_xyz", flag_value=False)2889 @click.option("--with-xyz", "enable_xyz", flag_value=True, default=True)2890 def cli(enable_xyz):2891 click.echo(repr(enable_xyz), nl=False)28922893 result = runner.invoke(cli, args, default_map=default_map)2894 assert result.exit_code == 0, result.output2895 assert result.output == repr(expected)289628972898@pytest.mark.parametrize(2899 ("opts", "args", "expected"),2900 [2901 # Non-boolean feature switch group: classic --upper/--lower2902 # pattern. The option with ``default=True`` acts as the default2903 # via the substitution rule (#3239) for non-boolean ``flag_value``.2904 pytest.param(2905 [2906 ("--upper", {"flag_value": "upper", "default": True}),2907 ("--lower", {"flag_value": "lower"}),2908 ],2909 [],2910 "upper",2911 id="string-default-true-substitutes-to-flag-value",2912 ),2913 pytest.param(2914 [2915 ("--upper", {"flag_value": "upper", "default": True}),2916 ("--lower", {"flag_value": "lower"}),2917 ],2918 ["--upper"],2919 "upper",2920 id="string-default-true-cmdline-positive",2921 ),2922 pytest.param(2923 [2924 ("--upper", {"flag_value": "upper", "default": True}),2925 ("--lower", {"flag_value": "lower"}),2926 ],2927 ["--lower"],2928 "lower",2929 id="string-default-true-cmdline-overrides",2930 ),2931 # Explicit literal string default beats sibling's absent default.2932 # Confirms the explicit-beats-absent rule applies regardless of type.2933 pytest.param(2934 [2935 ("--upper", {"flag_value": "upper", "default": "lower"}),2936 ("--lower", {"flag_value": "lower"}),2937 ],2938 [],2939 "lower",2940 id="string-explicit-default-wins-over-absent",2941 ),2942 pytest.param(2943 [2944 ("--upper", {"flag_value": "upper"}),2945 ("--lower", {"flag_value": "lower", "default": "upper"}),2946 ],2947 [],2948 "upper",2949 id="string-explicit-default-wins-from-second-position",2950 ),2951 # Empty string as ``flag_value``: still a legal value, including2952 # under the ``default=True`` substitution rule.2953 pytest.param(2954 [2955 ("--empty", {"flag_value": "", "default": True}),2956 ("--filled", {"flag_value": "filled"}),2957 ],2958 [],2959 "",2960 id="empty-string-flag-value-default-true",2961 ),2962 pytest.param(2963 [2964 ("--empty", {"flag_value": "", "default": True}),2965 ("--filled", {"flag_value": "filled"}),2966 ],2967 ["--empty"],2968 "",2969 id="empty-string-flag-value-cmdline",2970 ),2971 # Empty string as ``default``: explicit empty string beats2972 # the sibling's absent default.2973 pytest.param(2974 [2975 ("--upper", {"flag_value": "upper", "default": ""}),2976 ("--lower", {"flag_value": "lower"}),2977 ],2978 [],2979 "",2980 id="empty-string-explicit-default",2981 ),2982 # ``flag_value=None`` is a legal flag value: when the option is2983 # activated, the function receives ``None``.2984 pytest.param(2985 [2986 ("--none", {"flag_value": None, "default": "fallback"}),2987 ("--other", {"flag_value": "other"}),2988 ],2989 [],2990 "fallback",2991 id="none-flag-value-default-fallback",2992 ),2993 pytest.param(2994 [2995 ("--none", {"flag_value": None, "default": "fallback"}),2996 ("--other", {"flag_value": "other"}),2997 ],2998 ["--none"],2999 None,3000 id="none-flag-value-cmdline-passes-none",3001 ),3002 pytest.param(3003 [3004 ("--none", {"flag_value": None, "default": "fallback"}),3005 ("--other", {"flag_value": "other"}),3006 ],3007 ["--other"],3008 "other",3009 id="none-flag-value-cmdline-passes-other",3010 ),3011 # Explicit ``default=None`` is a real value (not absence) and3012 # must beat a sibling's absent default. Three-state pattern for3013 # non-boolean flag groups.3014 pytest.param(3015 [3016 ("--upper", {"flag_value": "upper", "default": None}),3017 ("--lower", {"flag_value": "lower"}),3018 ],3019 [],3020 None,3021 id="explicit-default-none-three-state",3022 ),3023 pytest.param(3024 [3025 ("--upper", {"flag_value": "upper", "default": None}),3026 ("--lower", {"flag_value": "lower"}),3027 ],3028 ["--upper"],3029 "upper",3030 id="explicit-default-none-cmdline-upper",3031 ),3032 pytest.param(3033 [3034 ("--upper", {"flag_value": "upper", "default": None}),3035 ("--lower", {"flag_value": "lower"}),3036 ],3037 ["--lower"],3038 "lower",3039 id="explicit-default-none-cmdline-lower",3040 ),3041 # Passing ``default=UNSET`` explicitly is the same as not passing3042 # ``default`` at all, so the sibling's explicit default wins.3043 pytest.param(3044 [3045 ("--upper", {"flag_value": "upper", "default": UNSET}),3046 ("--lower", {"flag_value": "lower", "default": "lower"}),3047 ],3048 [],3049 "lower",3050 id="unset-default-equivalent-to-absent",3051 ),3052 pytest.param(3053 [3054 ("--upper", {"flag_value": "upper", "default": UNSET}),3055 ("--lower", {"flag_value": "lower", "default": "lower"}),3056 ],3057 ["--upper"],3058 "upper",3059 id="unset-default-cmdline-still-works",3060 ),3061 # Neither option has a default: the slot resolves to ``None``3062 # because non-boolean flags do not auto-derive a default.3063 pytest.param(3064 [3065 ("--upper", {"flag_value": "upper"}),3066 ("--lower", {"flag_value": "lower"}),3067 ],3068 [],3069 None,3070 id="non-boolean-no-defaults-resolves-to-none",3071 ),3072 pytest.param(3073 [3074 ("--upper", {"flag_value": "upper"}),3075 ("--lower", {"flag_value": "lower"}),3076 ],3077 ["--upper"],3078 "upper",3079 id="non-boolean-no-defaults-cmdline-still-works",3080 ),3081 # Three-flag string group: explicit default wins from any3082 # position in the decorator stack.3083 pytest.param(3084 [3085 ("--upper", {"flag_value": "upper"}),3086 ("--mixed", {"flag_value": "MiXeD", "default": "MiXeD"}),3087 ("--lower", {"flag_value": "lower"}),3088 ],3089 [],3090 "MiXeD",3091 id="three-flags-explicit-default-in-middle",3092 ),3093 pytest.param(3094 [3095 ("--upper", {"flag_value": "upper"}),3096 ("--lower", {"flag_value": "lower"}),3097 ("--default-choice", {"flag_value": "chosen", "default": True}),3098 ],3099 [],3100 "chosen",3101 id="three-flags-default-true-substitution-last",3102 ),3103 # Both options have explicit defaults: last-wins, so the option3104 # declared last keeps the slot, regardless of value type.3105 pytest.param(3106 [3107 ("--upper", {"flag_value": "upper", "default": "first"}),3108 ("--lower", {"flag_value": "lower", "default": "second"}),3109 ],3110 [],3111 "second",3112 id="both-explicit-defaults-string-last-wins",3113 ),3114 # Mixed boolean and non-boolean ``flag_value`` in the same group3115 # is allowed. Both options here carry an explicit default, so last-wins3116 # picks the option declared last regardless of value type. The boolean3117 # ``default=False`` is a literal value (post-#3239), not a sentinel.3118 pytest.param(3119 [3120 ("--bool-flag", {"flag_value": True, "default": False}),3121 ("--str-flag", {"flag_value": "named", "default": "explicit"}),3122 ],3123 [],3124 "explicit",3125 id="mixed-bool-and-string-last-wins",3126 ),3127 pytest.param(3128 [3129 ("--str-flag", {"flag_value": "named", "default": "explicit"}),3130 ("--bool-flag", {"flag_value": True, "default": False}),3131 ],3132 [],3133 False,3134 id="mixed-bool-and-string-last-wins-swapped",3135 ),3136 # Empty string default coexisting with ``default=True``3137 # substitution: ``default=""`` is explicit, ``default=True`` is also3138 # explicit (and substitutes to the option's ``flag_value``). Last-wins3139 # picks the option declared last.3140 pytest.param(3141 [3142 ("--upper", {"flag_value": "upper", "default": True}),3143 ("--blank", {"flag_value": "blank", "default": ""}),3144 ],3145 [],3146 "",3147 id="default-true-vs-empty-string-last-wins",3148 ),3149 pytest.param(3150 [3151 ("--blank", {"flag_value": "blank", "default": ""}),3152 ("--upper", {"flag_value": "upper", "default": True}),3153 ],3154 [],3155 "upper",3156 id="default-true-vs-empty-string-last-wins-swapped",3157 ),3158 ],3159)3160def test_flag_group_competition_non_boolean(runner, opts, args, expected):3161 """Same arbitration rules as :func:`test_bool_flag_group_competition`,3162 but for feature-switch groups with non-boolean ``flag_value``.3163 """31643165 @click.command()3166 def cli(case):3167 click.echo(repr(case), nl=False)31683169 for opt_name, opt_kwargs in opts:3170 cli = click.option(opt_name, "case", **opt_kwargs)(cli)31713172 result = runner.invoke(cli, args)3173 assert result.exit_code == 0, result.output3174 assert result.output == repr(expected)317531763177@pytest.mark.parametrize(3178 ("default_a", "default_b", "args", "expected"),3179 [3180 # ``default=UNSET`` and an absent ``default`` keyword must produce3181 # identical behavior. Both options here are bare boolean flags, so3182 # both auto-derive ``False`` and last-wins applies (``--a`` is3183 # processed last); the value is ``False`` either way.3184 (UNSET, UNSET, [], False),3185 # ``default=UNSET`` on one side, explicit on the other: the explicit3186 # one wins regardless of decorator order.3187 (UNSET, True, [], True),3188 (True, UNSET, [], True),3189 (UNSET, False, [], False),3190 (False, UNSET, [], False),3191 # ``default=None`` is a real value, distinct from ``UNSET``, and3192 # remains explicit even when the sibling carries an explicit3193 # boolean default (3-state).3194 (None, UNSET, [], None),3195 (UNSET, None, [], None),3196 # Explicit ``None`` competing with explicit boolean. The decorator3197 # order in this test puts ``--a`` last in ``params``, so the value3198 # carried by ``default_a`` wins these "both explicit" ties under3199 # last-wins.3200 (None, True, [], None),3201 (True, None, [], True),3202 ],3203)3204def test_flag_group_unset_vs_none_vs_explicit(3205 runner, default_a, default_b, args, expected3206):3207 """``UNSET`` as an explicit ``default`` must be indistinguishable from3208 omitting ``default`` entirely, while ``None`` is a real explicit value.3209 """3210 a_kwargs = {"flag_value": True}3211 if default_a is not UNSET:3212 a_kwargs["default"] = default_a3213 elif default_a is UNSET:3214 # Pass UNSET explicitly to verify it's treated as absent. Skip when3215 # the test wants the absent-keyword case (matches default behavior3216 # because ``Parameter.__init__`` defaults ``default`` to ``UNSET``).3217 a_kwargs["default"] = UNSET32183219 b_kwargs = {"flag_value": False}3220 if default_b is not UNSET:3221 b_kwargs["default"] = default_b3222 elif default_b is UNSET:3223 b_kwargs["default"] = UNSET32243225 @click.command()3226 @click.option("--b", "state", **b_kwargs)3227 @click.option("--a", "state", **a_kwargs)3228 def cli(state):3229 click.echo(repr(state), nl=False)32303231 result = runner.invoke(cli, args)3232 assert result.exit_code == 0, result.output3233 assert result.output == repr(expected)323432353236def test_flag_group_competition_duplicate_option_name(runner):3237 """The same option name declared twice on the same command is a user3238 error.3239 """32403241 @click.command()3242 @click.option("--xyz", default="first")3243 @click.option("--xyz", default="second")3244 def cli(xyz):3245 click.echo(repr(xyz), nl=False)32463247 result = runner.invoke(cli, [])3248 assert result.exit_code == 13249 assert isinstance(result.exception, UserWarning)3250 assert "used more than once" in str(result.exception)325132523253@pytest.mark.parametrize(3254 ("args", "expected"),3255 [3256 (["--with-xyz", "--with-xyz"], True),3257 (["--without-xyz", "--without-xyz"], False),3258 (["--with-xyz", "--without-xyz", "--with-xyz"], True),3259 (["--without-xyz", "--with-xyz", "--without-xyz"], False),3260 ],3261)3262def test_flag_group_competition_repeated_cmdline(runner, args, expected):3263 """Duplicate flags passed in different order to the CLI."""32643265 @click.command()3266 @click.option("--without-xyz", "enable_xyz", flag_value=False)3267 @click.option("--with-xyz", "enable_xyz", flag_value=True, default=True)3268 def cli(enable_xyz):3269 click.echo(repr(enable_xyz), nl=False)32703271 result = runner.invoke(cli, args)3272 assert result.exit_code == 0, result.output3273 assert result.output == repr(expected)327432753276@pytest.mark.parametrize(3277 ("opts", "args", "expected"),3278 [3279 pytest.param(3280 [3281 ("--a", {"flag_value": "a"}),3282 ("--b", {"flag_value": "b"}),3283 ("--c", {"flag_value": "c"}),3284 ("--d", {"flag_value": "d"}),3285 ],3286 [],3287 None,3288 id="four-flags-no-defaults-resolves-to-none",3289 ),3290 pytest.param(3291 [3292 ("--a", {"flag_value": "a"}),3293 ("--b", {"flag_value": "b", "default": "from-b"}),3294 ("--c", {"flag_value": "c"}),3295 ("--d", {"flag_value": "d"}),3296 ],3297 [],3298 "from-b",3299 id="four-flags-only-second-explicit-wins",3300 ),3301 pytest.param(3302 [3303 ("--a", {"flag_value": "a"}),3304 ("--b", {"flag_value": "b", "default": "from-b"}),3305 ("--c", {"flag_value": "c"}),3306 ("--d", {"flag_value": "d", "default": "from-d"}),3307 ],3308 [],3309 "from-d",3310 id="four-flags-two-explicit-last-wins",3311 ),3312 pytest.param(3313 [3314 ("--a", {"flag_value": "a"}),3315 ("--b", {"flag_value": "b"}),3316 ("--c", {"flag_value": "c"}),3317 ("--d", {"flag_value": "d"}),3318 ],3319 ["--c"],3320 "c",3321 id="four-flags-cmdline-beats-everything",3322 ),3323 ],3324)3325def test_flag_group_competition_four_flags(runner, opts, args, expected):3326 """Arbitration rules applies to groups of any size."""33273328 @click.command()3329 def cli(case):3330 click.echo(repr(case), nl=False)33313332 for opt_name, opt_kwargs in opts:3333 cli = click.option(opt_name, "case", **opt_kwargs)(cli)33343335 result = runner.invoke(cli, args)3336 assert result.exit_code == 0, result.output3337 assert result.output == repr(expected)333833393340@pytest.mark.parametrize(3341 ("env", "default_map", "args", "expected"),3342 [3343 # ``auto_envvar_prefix`` produces an ``ENVIRONMENT`` source through a3344 # different code path than an explicit ``envvar=`` keyword. It still3345 # must beat any sibling default and be beaten by command-line input.3346 pytest.param(3347 {"AUTO_ENABLE_XYZ": "1"},3348 None,3349 [],3350 True,3351 id="auto-envvar-prefix-beats-default",3352 ),3353 pytest.param(3354 {"AUTO_ENABLE_XYZ": "1"},3355 None,3356 ["--without-xyz"],3357 False,3358 id="auto-envvar-prefix-loses-to-cmdline",3359 ),3360 # ``Sentinel.UNSET`` in ``default_map`` must be skipped (#32243361 # carve-out): the lookup falls through to the parameter default.3362 # Inside a feature switch group, the explicit ``default=True`` on3363 # ``--with-xyz`` then wins over the sibling's auto-``False``.3364 pytest.param(3365 {},3366 {"enable_xyz": UNSET},3367 [],3368 True,3369 id="unset-default-map-falls-through-to-explicit-default",3370 ),3371 pytest.param(3372 {},3373 {"enable_xyz": False},3374 [],3375 False,3376 id="real-default-map-beats-explicit-default",3377 ),3378 ],3379)3380def test_flag_group_competition_envvar_prefix_and_unset_default_map(3381 runner, monkeypatch, env, default_map, args, expected3382):3383 for name, value in env.items():3384 monkeypatch.setenv(name, value)33853386 @click.command()3387 @click.option("--without-xyz", "enable_xyz", flag_value=False)3388 @click.option("--with-xyz", "enable_xyz", flag_value=True, default=True)3389 def cli(enable_xyz):3390 click.echo(repr(enable_xyz), nl=False)33913392 invoke_kwargs = {"auto_envvar_prefix": "AUTO"}3393 if default_map is not None:3394 invoke_kwargs["default_map"] = default_map33953396 result = runner.invoke(cli, args, **invoke_kwargs)3397 assert result.exit_code == 0, result.output3398 assert result.output == repr(expected)339934003401@pytest.mark.parametrize(3402 ("flag_type", "args", "expect_output"),3403 [3404 (str, [], "Default\n"),3405 (str, ["--theflag"], "FlagValue\n"),
36 unmodified lines
modified:CHANGES.rst+8 added
55 unmodified lines
56- Show custom error messages from types when :func:`prompt` with57 ``hide_input=True`` fails validation, instead of always showing a58 generic message. Built-in type messages mask the input value.59 :issue:`2809` :pr:`3256`60- Fix feature switch groups (several ``flag_value`` options sharing one61 parameter name) silently dropping an explicit ``default`` when a sibling62 option without an explicit default was declared first. Arbitration is now63 source-aware: a more explicit :class:`ParameterSource` always wins, and64 within ``ParameterSource.DEFAULT``, an option that received an explicit65 ``default=`` keyword wins over a sibling whose default was auto-derived.66 The 8.3.x first-wins fallback for remaining ties was reverted to the67 pre-8.3.x last-wins fallback. :issue:`3403` :pr:`3404`6869Version 8.3.370-------------71
1364 unmodified lines