Skip to content
Myr

Streamline option flag management (#3641)

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

authored by Rowlando13 · committed by GitHub · parents b67832c, 8f30085 · Browse files · 2 files+231 added−157 removed
This commit

State

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

Diff stats

2 files+231 added−157 removed

  • other:+231 added−157 removed

2 files+231 added−157 removed

modified:src/click/core.py+226 added-157 removed
904 unmodified lines
905 ctx.params.update(kwargs)906 else:907 ctx = self908909 with augment_usage_errors(self):910 with ctx:911 return callback(*args, **kwargs)909 with augment_usage_errors(self), ctx:910 return callback(*args, **kwargs)911912 def forward(self, cmd: Command, /, *args: t.Any, **kwargs: t.Any) -> t.Any:913 """Similar to :meth:`invoke` but fills in default keyword914 arguments from the current context if the other command expects
773 unmodified lines
1688 #: default class. This makes a custom group class continue to make1689 #: custom groups.1690 #:1691 #: .. versionadded:: 8.01693 group_class: type[Group] | type[type] | None = None1692 group_class: type[Group | type] | None = None1693 # Literal[type] isn't valid, so use Type[type]16941695 commands: cabc.MutableMapping[str, Command]1696 invoke_without_command: bool
665 unmodified lines
2362 "is deprecated and still required. A deprecated "2363 f"{self.param_type_name} cannot be required."2364 )23652366 @staticmethod2367 def _hide_unset(value: t.Any) -> t.Any:2368 """Present the internal :data:`UNSET` sentinel as ``None`` at a boundary that2369 exposes a parameter's value (introspection, prompts), keeping the sentinel an2370 implementation detail.2371 """2372 return None if value is UNSET else value23732374 def to_info_dict(self) -> dict[str, t.Any]:2375 """Gather information that could be useful for a tool generating2376 user-facing documentation.2377
13 unmodified lines
2391 "type": self.type.to_info_dict(),2392 "required": self.required,2393 "nargs": self.nargs,2394 "multiple": self.multiple,2388 # We explicitly hide the :attr:`UNSET` value to the user, as we choose to2389 # make it an implementation detail. And because ``to_info_dict`` has been2390 # designed for documentation purposes, we return ``None`` instead.2391 "default": self.default if self.default is not UNSET else None,2395 "default": self._hide_unset(self.default),2396 "envvar": self.envvar,2397 }23982399 def __repr__(self) -> str:
529 unmodified lines
2929 hidden: bool29302931 _flag_needs_value: bool2932 is_flag: bool2929 is_bool_flag: bool2933 flag_value: t.Any2934 type: types.ParamType[t.Any]2935 default: t.Any | t.Callable[[], t.Any] | None29362937 count: bool2938 allow_from_autoenv: bool2939 help: str | None
28 unmodified lines
2968 super().__init__(2969 param_decls, type=type, multiple=multiple, deprecated=deprecated, **attrs2970 )29712972 # Phase 1: prompt-related attributes. ``_infer_flag_kind`` reads ``self.prompt``2973 # and ``self.prompt_required`` so this must run first.2974 if prompt is True:2975 if not self.name:2976 raise TypeError("'name' is required with 'prompt=True'.")2977
12 unmodified lines
2990 self.prompt_required = prompt_required2991 self.hide_input = hide_input2992 self.hidden = hidden29932987 # The _flag_needs_value property tells the parser that this option is a flag2988 # that cannot be used standalone and needs a value. With this information, the2989 # parser can determine whether to consider the next user-provided argument in2990 # the CLI as a value for this flag or as a new option.2991 # If prompt is enabled but not required, then it opens the possibility for the2992 # option to gets its value from the user.2993 self._flag_needs_value = self.prompt is not None and not self.prompt_required2994 # Phase 2: flag-kind inference.2995 self.is_flag, self._flag_needs_value = self._infer_flag_kind(2996 is_flag, flag_value2997 )29982995 # Auto-detect if this is a flag or not.2999 # Phase 3: type inference. Override the type set by :meth:`Parameter.__init__`3000 # when this option is a flag or a count.3001 self.type = self._pick_type(type, flag_value, count, self.is_flag)30023003 # Phase 4: store the raw ``flag_value`` and ``count`` settings.3004 # ``self.flag_value`` and ``self.default`` deliberately keep the :data:`UNSET`3005 # sentinel when the user didn't pass them. Auto-derived values are resolved3006 # lazily in :meth:`_resolve_lazy_default` and :attr:`flag_activation_value`.3007 # Keeping the raw values means ``is UNSET`` reliably answers "did the user pass3008 # this?": #3403 needs it for arbitration, and any future feature needing the3009 # same distinction can reuse it without reintroducing parallel "was it3010 # explicit?" tracking.3011 self.flag_value = flag_value3012 self.count = count3013 if count and self.default is UNSET:3014 self.default = 030153016 self.allow_from_autoenv = allow_from_autoenv3017 self.help = help3018 self.show_default = show_default3019 self.show_choices = show_choices3020 self.show_envvar = show_envvar30213022 # Phase 5: validate. Raises on illegal kwarg combinations.3023 self._validate(prompt, deprecated)30243025 @property3026 def is_bool_flag(self) -> bool:3027 """``True`` when this option is a flag with a boolean type.30283029 Derived from :attr:`is_flag` and :attr:`type`; computed on access so it cannot3030 drift if a subclass replaces :attr:`type` after construction.3031 """3032 return self.is_flag and isinstance(self.type, types.BoolParamType)30333034 @property3035 def flag_activation_value(self) -> t.Any:3036 """Value the function receives when this flag is activated on the command line.30373038 Resolves a missing :attr:`flag_value` to ``True`` for actual flag options and3039 ``None`` otherwise. Used by the parser bridge (:meth:`add_to_parser`) and the3040 runtime (:meth:`consume_value`) so :attr:`flag_value` can keep the :data:`UNSET`3041 sentinel for "did the user pass one?" introspection.3042 """3043 if self.flag_value is UNSET:3044 return True if self.is_flag else None3045 return self.flag_value30463047 def _infer_flag_kind(3048 self, is_flag: bool | None, flag_value: t.Any3049 ) -> tuple[bool, bool]:3050 """Resolve ``is_flag`` and the parser hint ``_flag_needs_value``.30513052 Returns ``(is_flag, flag_needs_value)``, where ``_flag_needs_value`` tells the3053 parser this option is a flag that cannot be used standalone and needs a value.3054 The parser uses it to decide whether to treat the next CLI token as the flag's3055 value or as a new option. If ``prompt`` is enabled with3056 ``prompt_required=False``, it opens the door for an interactive value, hence the3057 initial condition. Ref: https://github.com/pallets/click/issues/30843058 """3059 needs_value = self.prompt is not None and not self.prompt_required30603061 if is_flag is None:3062 # Implicitly a flag because flag_value was set.3063 if flag_value is not UNSET:2999 is_flag = True3064 return True, needs_value3065 # Not a flag, but when used as a flag it shows a prompt.3001 elif self._flag_needs_value:3002 is_flag = False3066 if needs_value:3067 return False, needs_value3068 # Implicitly a flag because secondary options names were given.3004 elif self.secondary_opts:3005 is_flag = True3069 if self.secondary_opts:3070 return True, needs_value3071 return False, needs_value30723007 # The option is explicitly not a flag, but to determine whether or not it needs3008 # value, we need to check if `flag_value` or `default` was set. Either one is3009 # sufficient.3010 # Ref: https://github.com/pallets/click/issues/30843011 elif is_flag is False and not self._flag_needs_value:3012 self._flag_needs_value = flag_value is not UNSET or self.default is UNSET3073 if is_flag is False and not needs_value:3074 # Explicit ``is_flag=False`` with a flag-like value/default still makes the3075 # option flag-shaped to the parser.3076 needs_value = flag_value is not UNSET or self.default is UNSET30773014 if is_flag:3015 # Set missing default for flags if not explicitly required or prompted.3016 if self.default is UNSET and not self.required and not self.prompt:3017 if multiple:3018 self.default = ()3078 return bool(is_flag), needs_value30793020 # Auto-detect the type of the flag based on the flag_value.3021 if type is None:3022 # A flag without a flag_value is a boolean flag.3023 if flag_value is UNSET:3024 self.type: types.ParamType[t.Any] = types.BoolParamType()3025 # If the flag value is a boolean, use BoolParamType.3026 elif isinstance(flag_value, bool):3027 self.type = types.BoolParamType()3028 # Otherwise, guess the type from the flag value.3029 else:3030 guessed = types.convert_type(None, flag_value)3031 if (3032 isinstance(guessed, types.StringParamType)3033 and not isinstance(flag_value, str)3034 and flag_value is not None3035 ):3036 # The flag_value type couldn't be auto-detected3037 # (not str, int, float, or bool). Since flag_value3038 # is a programmer-provided Python object, not CLI3039 # input, pass it through unchanged instead of3040 # stringifying it.3041 self.type = types.UNPROCESSED3042 else:3043 self.type = guessed3080 def _pick_type(3081 self,3082 type_arg: t.Any,3083 flag_value: t.Any,3084 count: bool,3085 is_flag: bool,3086 ) -> types.ParamType[t.Any]:3087 """Pick the final :class:`ParamType` for this option.30883045 self.is_flag = bool(is_flag)3046 self.is_bool_flag = self.is_flag and isinstance(self.type, types.BoolParamType)3047 self.flag_value = flag_value3089 :meth:`Parameter.__init__` already stored ``self.type`` from the explicit3090 ``type`` argument or from ``default``. This method either returns that as-is, or3091 overrides it for flag and count options (which are inferred from ``flag_value``3092 rather than ``default``).3093 """3094 if type_arg is not None:3095 return self.type30963049 # Set boolean flag default to False if unset and not required.3050 if self.is_bool_flag:3051 if self.default is UNSET and not self.required:3052 self.default = False30533054 # The alignment of default to the flag_value is resolved lazily in3055 # get_default() to prevent callable flag_values (like classes) from3056 # being instantiated. Refs:3057 # https://github.com/pallets/click/issues/31213058 # https://github.com/pallets/click/issues/3024#issuecomment-31461994613059 # https://github.com/pallets/click/pull/3030/commits/06847da30603061 # Set the default flag_value if it is not set.3062 if self.flag_value is UNSET:3063 if self.is_flag:3064 self.flag_value = True3065 else:3066 self.flag_value = None30673068 # Counting.3069 self.count = count3097 if count:3071 if type is None:3072 self.type = types.IntRange(min=0)3098 return types.IntRange(min=0)3073 if self.default is UNSET:3074 self.default = 030993076 self.allow_from_autoenv = allow_from_autoenv3077 self.help = help3078 self.show_default = show_default3079 self.show_choices = show_choices3080 self.show_envvar = show_envvar3100 if not is_flag:3101 return self.type31023082 if __debug__:3083 if deprecated and prompt:3084 raise ValueError("`deprecated` options cannot use `prompt`.")3103 # A flag without a flag_value is a boolean flag.3104 if flag_value is UNSET or isinstance(flag_value, bool):3105 return types.BoolParamType()31063086 if self.nargs == -1:3087 raise TypeError("nargs=-1 is not supported for options.")3107 guessed: types.ParamType[t.Any] = types.convert_type(None, flag_value)3108 if (3109 isinstance(guessed, types.StringParamType)3110 and not isinstance(flag_value, str)3111 and flag_value is not None3112 ):3113 # The flag_value type couldn't be auto-detected (not str, int, float, or3114 # bool). Since flag_value is a programmer-provided Python object, not CLI3115 # input, pass it through unchanged instead of stringifying it.3116 return types.UNPROCESSED3117 return guessed31183089 if not self.is_bool_flag and self.secondary_opts:3090 raise TypeError("Secondary flag is not valid for non-boolean flag.")3119 def _resolve_lazy_default(self, value: t.Any) -> t.Any:3120 """Apply lazy auto-derivations to a default-style value.31213092 if self.is_bool_flag and self.hide_input and self.prompt is not None:3093 raise TypeError(3094 "'prompt' with 'hide_input' is not valid for boolean flag."3095 )3122 Shared between :meth:`get_default` (the runtime path) and :meth:`to_info_dict`3123 (the introspection path) so the two views cannot drift apart. Callables are3124 *not* invoked here: that is :meth:`get_default`'s responsibility. Rules:31253097 if self.count:3098 if self.multiple:3099 raise TypeError("'count' is not valid with 'multiple'.")3126 * ``UNSET`` resolves to ``False`` for a non-required boolean flag, and to ``()``3127 for a non-required, non-prompted multi flag.3128 * ``True`` resolves to :attr:`flag_value` for a non-boolean flag (the "activate3129 this flag by default" shorthand). Boolean flags keep ``True`` as a literal.3130 """3131 if value is UNSET and self.is_flag:3132 if self.multiple and not self.required and not self.prompt:3133 return ()3134 if self.is_bool_flag and not self.required:3135 return False3136 if value is True and self.is_flag and not self.is_bool_flag:3137 # Use ``flag_activation_value`` so an unset ``flag_value`` resolves to3138 # ``True`` (the bool-flag activation value) rather than leaking the3139 # :data:`UNSET` sentinel.3140 return self.flag_activation_value3141 return value31423101 if self.is_flag:3102 raise TypeError("'count' is not valid with 'is_flag'.")3143 def _validate(self, prompt: bool | str, deprecated: bool | str) -> None:3144 """Raise :class:`TypeError` / :class:`ValueError` on illegal kwarg combinations.31453146 Called once, after every other attribute has been assigned, so each check can3147 read the final state.3148 """3149 if not __debug__:3150 return3151 if deprecated and prompt:3152 raise ValueError("`deprecated` options cannot use `prompt`.")3153 if self.nargs == -1:3154 raise TypeError("nargs=-1 is not supported for options.")3155 if not self.is_bool_flag and self.secondary_opts:3156 raise TypeError("Secondary flag is not valid for non-boolean flag.")3157 if self.is_bool_flag and self.hide_input and self.prompt is not None:3158 raise TypeError("'prompt' with 'hide_input' is not valid for boolean flag.")3159 if self.count:3160 if self.multiple:3161 raise TypeError("'count' is not valid with 'multiple'.")3162 if self.is_flag:3163 raise TypeError("'count' is not valid with 'is_flag'.")31643165 def to_info_dict(self) -> dict[str, t.Any]:3166 """3167 .. versionchanged:: 8.5.03168 ``default`` and ``flag_value`` reflect the auto-derived values (``False``3169 for unset boolean-flag defaults, ``True`` for unset boolean-flag activation3170 values, etc.) when no explicit value was passed, matching what the function3171 would receive at call time.31723173 .. versionchanged:: 8.3.03174 Returns ``None`` for the :attr:`flag_value` if it was not set.3175 """3176 info_dict = super().to_info_dict()3177 info_dict.update(3178 default=self._hide_unset(self._resolve_lazy_default(self.default)),3179 help=self.help,3180 prompt=self.prompt,3181 is_flag=self.is_flag,3114 # We explicitly hide the :attr:`UNSET` value to the user, as we choose to3115 # make it an implementation detail. And because ``to_info_dict`` has been3116 # designed for documentation purposes, we return ``None`` instead.3117 flag_value=self.flag_value if self.flag_value is not UNSET else None,3182 flag_value=self.flag_activation_value,3183 count=self.count,3184 hidden=self.hidden,3185 )3186 return info_dict
2 unmodified lines
3189 self, ctx: Context, call: bool = True3190 ) -> t.Any | t.Callable[[], t.Any] | None:3191 """Return the default value for this option.31923128 For non-boolean flag options, ``default=True`` is treated as a sentinel3129 meaning "activate this flag by default" and is resolved to3130 :attr:`flag_value`. For example, with ``--upper/--lower`` feature3131 switches where ``flag_value="upper"`` and ``default=True``, the default3132 resolves to ``"upper"``.3193 Several auto-derived defaults are resolved lazily here rather than eagerly in3194 :meth:`__init__`. This keeps :attr:`default` raw at construction time, so3195 ``self.default is UNSET`` reliably answers "did the user pass a default?" for3196 feature-switch-group arbitration and for anything else that needs to distinguish3197 "absent" from a chosen value. The resolution rules live in3198 :meth:`_resolve_lazy_default`.31993134 .. caution::3135 This substitution only applies to non-boolean flags3136 (:attr:`is_bool_flag` is ``False``). For boolean flags, ``True`` is3137 a legitimate Python value and ``default=True`` is returned as-is.3200 .. versionchanged:: 8.5.03201 ``UNSET`` defaults for boolean and multi flags are now resolved here instead3202 of being coerced in :meth:`__init__`. Reading :attr:`default` directly3203 returns the user-supplied value (or ``UNSET`` if none was passed) rather3204 than the auto-derived one.32053206 .. versionchanged:: 8.3.33140 ``default=True`` is no longer substituted with ``flag_value`` for3141 boolean flags, fixing negative boolean flags like3207 ``default=True`` is no longer substituted with ``flag_value`` for boolean3208 flags, fixing negative boolean flags like3209 ``flag_value=False, default=True``.3210 """3144 value = super().get_default(ctx, call=False)31453146 # Resolve default=True to flag_value lazily (here instead of3147 # __init__) to prevent callable flag_values (like classes) from3148 # being instantiated by the callable check below.3149 if value is True and self.is_flag and not self.is_bool_flag:3150 value = self.flag_value3151 elif call and callable(value):3211 raw = super().get_default(ctx, call=False)3212 value = self._resolve_lazy_default(raw)3213 # Only invoke the value as a callable when the lazy resolver passed it through3214 # unchanged. If the resolver substituted ``True`` -> :attr:`flag_value`, the3215 # result is the programmer-supplied ``flag_value`` (often a class or enum),3216 # which must NOT be instantiated here. See3217 # https://github.com/pallets/click/issues/3121.3218 if value is raw and call and callable(value):3219 value = value()31533220 return value32213222 def get_error_hint(self, ctx: Context | None) -> str:3223 result = super().get_error_hint(ctx)
89 unmodified lines
3313 obj=self,3314 opts=self.opts,3315 dest=self.name,3316 action=action,3317 # ``flag_activation_value`` resolves UNSET to the right parser-store3318 # constant (``True`` for bool flags) so the raw :attr:`flag_value`3319 # can keep the sentinel.3251 const=self.flag_value,3320 const=self.flag_activation_value,3321 )3322 else:3323 parser.add_option(3324 obj=self,
172 unmodified lines
3497 return prompt(3498 self.prompt,3499 # Use ``None`` to inform the prompt() function to reiterate until a valid3500 # value is provided by the user if we have no default.3432 default=None if default is UNSET else default,3501 default=self._hide_unset(default),3502 type=self.type,3503 hide_input=self.hide_input,3504 show_choices=self.show_choices,3505 confirmation_prompt=self.confirmation_prompt,
47 unmodified lines
3553 # Non-boolean flags are more liberal in what they accept. But a flag being a3554 # flag, its envvar value still needs to be analyzed to determine if the flag is3555 # activated or not.3556 if self.is_flag and not self.is_bool_flag:3488 # If the flag_value is set and match the envvar value, return it3489 # directly.3490 if self.flag_value is not UNSET and rv == self.flag_value:3557 # An exact match against ``flag_value`` (a non-bool flag always has one3558 # explicitly set) returns it directly. Otherwise the value is analyzed as a3559 # boolean: a truthy reading activates the flag and the function receives3560 # ``flag_value``; a falsy reading produces ``False``; an unrecognized3561 # reading falls through as ``None``. Folding the substitution here means3562 # :meth:`consume_value` no longer has to repeat it in a source-checked3563 # branch.3564 if rv == self.flag_value:3565 return self.flag_value3492 # Analyze the envvar value as a boolean to know if the flag is3493 # activated or not.3494 return types.BoolParamType.str_to_bool(rv)3566 parsed = types.BoolParamType.str_to_bool(rv)3567 if parsed is None:3568 return None3569 return self.flag_value if parsed else False35703571 # Split the envvar value if it is allowed to be repeated.3572 value_depth = (self.nargs != 1) + bool(self.multiple)3573 if value_depth > 0:
18 unmodified lines
3592 :meta private:3593 """3594 value, source = super().consume_value(ctx, opts)35953521 # The parser will emit a sentinel value if the option is allowed to as a flag3522 # without a value.3596 # The parser emits a sentinel when a flag is allowed to be used without a value.3597 # Resolve it to a prompt or to the activation value depending on the option's3598 # configuration.3599 if value is FLAG_NEEDS_VALUE:3524 # If the option allows for a prompt, we start an interaction with the user.3600 # If the option allows for a prompt, start an interaction with the user.3601 if self.prompt is not None and not ctx.resilient_parsing:3602 value = self.prompt_for_value(ctx)3603 source = ParameterSource.PROMPT3528 # Else the flag takes its flag_value as value.3604 # Else the flag takes its activation value (resolves UNSET).3605 else:3530 value = self.flag_value3606 value = self.flag_activation_value3607 source = ParameterSource.COMMANDLINE36083533 # A flag which is activated always returns the flag value, unless the value3534 # comes from the explicitly sets default.3609 # Re-interpret a multiple option that the parser sent through as a list still3610 # containing the FLAG_NEEDS_VALUE sentinel, replacing each occurrence with the3611 # activation value.3612 elif (3536 self.is_flag3537 and value is True3538 and not self.is_bool_flag3539 and source < ParameterSource.DEFAULT_MAP3540 ):3541 value = self.flag_value35423543 # Re-interpret a multiple option which has been sent as-is by the parser.3544 # Here we replace each occurrence of value-less flags (marked by the3545 # FLAG_NEEDS_VALUE sentinel) with the flag_value.3546 elif (3613 self.multiple3614 and value is not UNSET3615 and isinstance(value, cabc.Iterable)3616 and source < ParameterSource.DEFAULT_MAP3617 and any(v is FLAG_NEEDS_VALUE for v in value)3618 ):3553 value = [self.flag_value if v is FLAG_NEEDS_VALUE else v for v in value]3619 value = [3620 self.flag_activation_value if v is FLAG_NEEDS_VALUE else v3621 for v in value3622 ]3623 source = ParameterSource.COMMANDLINE36243625 # The value wasn't set, or used the param's default, prompt for one to the user3626 # if prompting is enabled.
166 unmodified lines
modified:CHANGES.md+5 added
25 unmodified lines
26 share a name to compete for the same value (feature switches).27 {issue}`2819` {pr}`3678`28- `unstyle` and the ANSI handling behind help-text wrapping now strip the full29 CSI escape-sequence grammar.30- Streamline `Option` flag handling: the flag-kind, type, lazy-default and31 validation steps in `Option.__init__` move into focused helpers, and32 `flag_value` and `default` keep their unset sentinel at construction33 (resolved lazily on read) so `is UNSET` reliably tells a user-supplied value34 from an auto-derived one. Behavior is unchanged. {pr}`3641`3536## Version 8.4.23738Released 2026-06-24
1561 unmodified lines