Skip to content
Myr

Merge branch 'main' into flag-value-unprocessed-auto-detect

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

authored by Rowlando13 · committed by GitHub · parents 235e03e, c8da1fc · Browse files · 22 files+339 added−149 removed
This commit

State

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

Diff stats

22 files+339 added−149 removed

  • tests:+51 added−12 removed
  • other:+288 added−137 removed

22 files+339 added−149 removed

modified:docs/commands.md+29 added
349 unmodified lines
350 }351 })352```353354### Multi-value parameters355356When a `default_map` value is a string for a parameter with `nargs > 1` or a357{class}`Tuple` type, the string is split automatically, the same way an358environment variable would be. By default, values are split on whitespace. See359[Multiple Options from Environment360Values](options.md#multiple-options-from-environment-values) for details on361splitting behavior.362363```python364default_map = {365 "draw": {366 "point": "3 4", # split into ("3", "4") for nargs=2367 "color": "red", # passed as-is for nargs=1368 }369}370```371372You can also pass an already-structured tuple or list, which will be used as-is373without splitting:374375```python376default_map = {377 "draw": {378 "point": (3, 4), # used directly379 }380}381```382383## Context Defaults384385```{versionadded} 2.0386```
81 unmodified lines
modified:docs/conf.py+1 added
29 unmodified lines
30}31intersphinx_mapping = {32 "python": ("https://docs.python.org/3/", None),33}34myst_heading_anchors = 33536# HTML -----------------------------------------------------------------3738html_theme = "click"
20 unmodified lines
modified:docs/contributing.md+27 added-4 removed
modified:docs/parameter-types.md+21 added-2 removed
68 unmodified lines
69The resulting value from an option will always be one of the originally passed choices70regardless of `case_sensitive`.71```7273```{versionchanged} 8.4.074{class}`Choice` is now generic. Parameterize it with the choice value type75({class}`!Choice[HashType]` for an enum, {class}`!Choice[str]` for plain76strings) to enable type-checked consumers.77```7879(ranges)=8081### Int and Float Ranges82
75 unmodified lines
158To implement a custom type, you need to subclass the {class}`ParamType` class. For simple cases, passing a Python159function that fails with a `ValueError` is also supported, though discouraged. Override the {meth}`~ParamType.convert`160method to convert the value from a string to the correct type.161162{class}`ParamType` is generic in the converted value type: parameterize it with163the type returned by `convert` so that consumers (and type checkers) can rely164on the narrowed return type.165166The following code implements an integer type that accepts hex and octal numbers in addition to normal integers, and167converts them into regular integers.168169```python170import click171172162class BasedIntParamType(click.ParamType):173class BasedIntParamType(click.ParamType[int]):174 name = "integer"175165 def convert(self, value, param, ctx):176 def convert(self, value, param, ctx) -> int:177 if isinstance(value, int):178 return value179180 try:
4 unmodified lines
185 return int(value, 10)186 except ValueError:187 self.fail(f"{value!r} is not a valid integer", param, ctx)188189190BASED_INT = BasedIntParamType()191```192193The {attr}`~ParamType.name` attribute is optional and is used for documentation. Call {meth}`~ParamType.fail` if
1 unmodified line
195196Values from user input or the command line will be strings, but default values and Python arguments may already be the197correct type. The custom type should check at the top if the value is already valid and pass it through to support those198cases.199200```{versionchanged} 8.4.0201{class}`ParamType` is now a generic abstract base class. Parameterize it with202the converted value type ({class}`!ParamType[int]` for an integer-returning203type) so that {meth}`~ParamType.convert` and downstream consumers carry the204narrowed type.205```
modified:docs/shell-completion.md+1 added-1 removed
118 unmodified lines
119120In this example, the type will suggest environment variables that start with the incomplete value.121122```python123class EnvVarType(ParamType):123class EnvVarType(ParamType[str]):124 name = "envvar"125126 def shell_complete(self, ctx, param, incomplete):127 return [
122 unmodified lines
modified:docs/support-multiple-versions.md+1 added-1 removed
modified:examples/aliases/aliases.py+1 added-1 removed
38 unmodified lines
39 file and with a bit of magic.40 """4142 def get_command(self, ctx, cmd_name):43 # Step one: bulitin commands as normal43 # Step one: built-in commands as normal44 rv = click.Group.get_command(self, ctx, cmd_name)45 if rv is not None:46 return rv47
96 unmodified lines
modified:examples/repo/repo.py+1 added-1 removed
46 unmodified lines
4748 This tool is supposed to look like a distributed version control49 system to show how something like this can be structured.50 """51 # Create a repo object and remember it as as the context object. From51 # Create a repo object and remember it as the context object. From52 # this point onwards other commands can refer to it by using the53 # @pass_repo decorator.54 ctx.obj = Repo(os.path.abspath(repo_home))55 ctx.obj.verbose = verbose
111 unmodified lines
modified:examples/validation/validation.py+2 added-2 removed
7 unmodified lines
8 raise click.BadParameter("Should be a positive, even integer.")9 return value101112class URL(click.ParamType):12class URL(click.ParamType[urlparse.ParseResult]):13 name = "url"1415 def convert(self, value, param, ctx):15 def convert(self, value, param, ctx) -> urlparse.ParseResult:16 if not isinstance(value, tuple):17 value = urlparse.urlparse(value)18 if value.scheme not in ("http", "https"):19 self.fail(
29 unmodified lines
modified:src/click/core.py+13 added-8 removed
194 unmodified lines
195 :param parent: the parent context.196 :param info_name: the info name for this invocation. Generally this197 is the most descriptive name for the script or198 command. For the toplevel script it is usually199 the name of the script, for commands below it it's199 the name of the script, for commands below that it's200 the name of the script.201 :param obj: an arbitrary object of user data.202 :param auto_envvar_prefix: the prefix to use for automatic environment203 variables. If this is `None` then reading
890 unmodified lines
1094 return None10951096 # Cache the help option object in private _help_option attribute to1097 # avoid creating it multiple times. Not doing this will break the1098 # callback odering by iter_params_for_processing(), which relies on1098 # callback ordering by iter_params_for_processing(), which relies on1099 # object comparison.1100 if self._help_option is None:1101 # Avoid circular import.1102 from .decorators import help_option
1045 unmodified lines
21482149 def __init__(2150 self,2151 param_decls: cabc.Sequence[str] | None = None,2152 type: types.ParamType | t.Any | None = None,2152 type: types.ParamType[t.Any] | t.Any | None = None,2153 required: bool = False,2154 # XXX The default historically embed two concepts:2155 # - the declaration of a Parameter object carrying the default (handy to2156 # arbitrage the default value of coupled Parameters sharing the same
23 unmodified lines
2180 self.secondary_opts: list[str]2181 self.name, self.opts, self.secondary_opts = self._parse_decls(2182 param_decls or (), expose_value2183 )2184 self.type: types.ParamType = types.convert_type(type, default)2184 self.type: types.ParamType[t.Any] = types.convert_type(type, default)21852186 # Default nargs to what the type tells us if we have that2187 # information available.2188 if nargs is None:
166 unmodified lines
2355 if default_map_value is not None or ctx._default_map_has(self.name):2356 value = default_map_value2357 source = ParameterSource.DEFAULT_MAP23582359 # A string from default_map must be split for multi-value2360 # parameters, matching value_from_envvar behavior.2361 if isinstance(value, str) and self.nargs != 1:2362 value = self.type.split_envvar_value(value)23632364 if value is UNSET:2365 default_value = self.get_default(ctx)2366 if default_value is not UNSET:2367 value = default_value
284 unmodified lines
2652 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]:2653 """Return a list of completions for the incomplete value. If a2654 ``shell_complete`` function was given during init, it is used.2655 Otherwise, the :attr:`type`2651 :meth:`~click.types.ParamType.shell_complete` function is used.2656 :meth:`~click.types.ParamType[t.Any].shell_complete` function is used.26572658 :param ctx: Invocation context for this command.2659 :param incomplete: Value being completed. May be empty.2660
98 unmodified lines
2759 flag_value: t.Any = UNSET,2760 multiple: bool = False,2761 count: bool = False,2762 allow_from_autoenv: bool = True,2758 type: types.ParamType | t.Any | None = None,2763 type: types.ParamType[t.Any] | t.Any | None = None,2764 help: str | None = None,2765 hidden: bool = False,2766 show_choices: bool = True,2767 show_envvar: bool = False,
67 unmodified lines
2835 # Auto-detect the type of the flag based on the flag_value.2836 if type is None:2837 # A flag without a flag_value is a boolean flag.2838 if flag_value is UNSET:2834 self.type: types.ParamType = types.BoolParamType()2839 self.type: types.ParamType[t.Any] = types.BoolParamType()2840 # If the flag value is a boolean, use BoolParamType.2841 elif isinstance(flag_value, bool):2842 self.type = types.BoolParamType()2843 # Otherwise, guess the type from the flag value.
23 unmodified lines
2867 if self.is_bool_flag:2868 if self.default is UNSET and not self.required:2869 self.default = False28702866 # The alignement of default to the flag_value is resolved lazily in2871 # The alignment of default to the flag_value is resolved lazily in2872 # get_default() to prevent callable flag_values (like classes) from2873 # being instantiated. Refs:2874 # https://github.com/pallets/click/issues/31212875 # https://github.com/pallets/click/issues/3024#issuecomment-3146199461
625 unmodified lines
modified:src/click/parser.py+1 added-1 removed
419 unmodified lines
420 break421422 # If we got any unknown options we recombine the string of the423 # remaining options and re-attach the prefix, then report that424 # to the state as new larg. This way there is basic combinatorics424 # to the state as new large. This way there is basic combinatorics425 # that can be achieved while still ignoring unknown arguments.426 if self.ignore_unknown_options and unknown_options:427 state.largs.append(f"{prefix}{''.join(unknown_options)}")428
104 unmodified lines
modified:src/click/termui.py+2 added-2 removed
61 unmodified lines
62 suffix: str,63 show_default: bool | str = False,64 default: t.Any | None = None,65 show_choices: bool = True,66 type: ParamType | None = None,66 type: ParamType[t.Any] | None = None,67) -> str:68 prompt = text69 if type is not None and show_choices and isinstance(type, Choice):70 prompt += f" ({', '.join(map(str, type.choices))})"
15 unmodified lines
86 text: str,87 default: t.Any | None = None,88 hide_input: bool = False,89 confirmation_prompt: bool | str = False,90 type: ParamType | t.Any | None = None,90 type: ParamType[t.Any] | t.Any | None = None,91 value_proc: t.Callable[[str], t.Any] | None = None,92 prompt_suffix: str = ": ",93 show_default: bool | str = True,94 err: bool = False,
797 unmodified lines
modified:src/click/types.py+145 added-97 removed
1from __future__ import annotations23import abc4import collections.abc as cabc5import enum6import os7import stat8import sys9import typing as t10import uuid11from datetime import datetime12from gettext import gettext as _13from gettext import ngettext14
13 unmodified lines
2829ParamTypeValue = t.TypeVar("ParamTypeValue")303130class ParamType:32class ParamTypeInfoDict(t.TypedDict):33 param_type: str34 name: str353637class ParamType(t.Generic[ParamTypeValue], abc.ABC):38 """Represents the type of a parameter. Validates and converts values39 from the command line or Python into the correct type.4041 To implement a custom type, subclass and implement at least the
23 unmodified lines
65 #: are split by ``os.path.pathsep`` by default (":" on Unix and ";" on66 #: Windows).67 envvar_list_splitter: t.ClassVar[str | None] = None6862 def to_info_dict(self) -> dict[str, t.Any]:69 def to_info_dict(self) -> ParamTypeInfoDict:70 """Gather information that could be useful for a tool generating71 user-facing documentation.7273 Use :meth:`click.Context.to_info_dict` to traverse the entire
17 unmodified lines
91 self,92 value: t.Any,93 param: Parameter | None = None,94 ctx: Context | None = None,88 ) -> t.Any:95 ) -> ParamTypeValue | None:96 if value is not None:97 return self.convert(value, param, ctx)98 return None99100 def get_metavar(self, param: Parameter, ctx: Context) -> str | None:101 """Returns the metavar default for this param if it provides one."""102
5 unmodified lines
108 """109110 def convert(111 self, value: t.Any, param: Parameter | None, ctx: Context | None104 ) -> t.Any:112 ) -> ParamTypeValue:113 """Convert the value to the correct type. This is not called if114 the value is ``None`` (the missing value).115116 This must accept string values from the command line, as well as
11 unmodified lines
128 its value. May be ``None``.129 :param ctx: The current context that arrived at this value. May130 be ``None``.131 """124 return value132 # The default returns the value as-is so subclasses that only customize133 # metadata are not forced to redeclare ``convert``.134 return t.cast("ParamTypeValue", value)135136 def split_envvar_value(self, rv: str) -> cabc.Sequence[str]:137 """Given a value from an environment variable this splits it up138 into small chunks depending on the defined envvar list splitter.
30 unmodified lines
169 """170 return []171172163class CompositeParamType(ParamType):173class CompositeParamType(ParamType[ParamTypeValue]):174 is_composite = True175176 @property167 def arity(self) -> int: # type: ignore168 raise NotImplementedError()177 @abc.abstractmethod178 def arity(self) -> int: ... # type: ignore[override]179180171class FuncParamType(ParamType):172 def __init__(self, func: t.Callable[[t.Any], t.Any]) -> None:181class FuncParamTypeInfoDict(ParamTypeInfoDict):182 func: t.Callable[[t.Any], t.Any]183184185class FuncParamType(ParamType[ParamTypeValue]):186 def __init__(self, func: t.Callable[[t.Any], ParamTypeValue]) -> None:187 self.name: str = func.__name__188 self.func = func189176 def to_info_dict(self) -> dict[str, t.Any]:177 info_dict = super().to_info_dict()178 info_dict["func"] = self.func179 return info_dict190 def to_info_dict(self) -> FuncParamTypeInfoDict:191 return {"func": self.func, **super().to_info_dict()}192193 def convert(194 self, value: t.Any, param: Parameter | None, ctx: Context | None183 ) -> t.Any:195 ) -> ParamTypeValue:196 try:197 return self.func(value)198 except ValueError:199 try:
3 unmodified lines
203204 self.fail(value, param, ctx)205206195class UnprocessedParamType(ParamType):207class UnprocessedParamType(ParamType[t.Any]):208 name = "text"209210 def convert(211 self, value: t.Any, param: Parameter | None, ctx: Context | None
3 unmodified lines
215 def __repr__(self) -> str:216 return "UNPROCESSED"217218207class StringParamType(ParamType):219class StringParamType(ParamType[str]):220 name = "text"221222 def convert(223 self, value: t.Any, param: Parameter | None, ctx: Context | None212 ) -> t.Any:224 ) -> str:225 if isinstance(value, bytes):226 enc = _get_argv_encoding()227 try:228 value = value.decode(enc)
5 unmodified lines
234 except UnicodeError:235 value = value.decode("utf-8", "replace")236 else:237 value = value.decode("utf-8", "replace")226 return value238 return value # type: ignore[no-any-return]239 return str(value)240241 def __repr__(self) -> str:242 return "STRING"243244233class Choice(ParamType, t.Generic[ParamTypeValue]):245class ChoiceInfoDict(ParamTypeInfoDict):246 choices: cabc.Sequence[t.Any]247 case_sensitive: bool248249250class Choice(ParamType[ParamTypeValue], t.Generic[ParamTypeValue]):251 """The choice type allows a value to be checked against a fixed set252 of supported values.253254 You may pass any iterable value which will be converted to a tuple
22 unmodified lines
277 ) -> None:278 self.choices: cabc.Sequence[ParamTypeValue] = tuple(choices)279 self.case_sensitive = case_sensitive280264 def to_info_dict(self) -> dict[str, t.Any]:265 info_dict = super().to_info_dict()266 info_dict["choices"] = self.choices267 info_dict["case_sensitive"] = self.case_sensitive268 return info_dict281 def to_info_dict(self) -> ChoiceInfoDict:282 return {283 "choices": self.choices,284 "case_sensitive": self.case_sensitive,285 **super().to_info_dict(),286 }287288 def _normalized_mapping(289 self, ctx: Context | None = None290 ) -> cabc.Mapping[ParamTypeValue, str]:
124 unmodified lines
415416 return [CompletionItem(c) for c in matched]417418401class DateTime(ParamType):419class DateTimeInfoDict(ParamTypeInfoDict):420 formats: cabc.Sequence[str]421422423class DateTime(ParamType[datetime]):424 """The DateTime type converts date strings into `datetime` objects.425426 The format strings which are checked are configurable, but default to some427 common (non-timezone aware) ISO 8601 formats.
21 unmodified lines
449 "%Y-%m-%dT%H:%M:%S",450 "%Y-%m-%d %H:%M:%S",451 ]452431 def to_info_dict(self) -> dict[str, t.Any]:432 info_dict = super().to_info_dict()433 info_dict["formats"] = self.formats434 return info_dict453 def to_info_dict(self) -> DateTimeInfoDict:454 return {"formats": self.formats, **super().to_info_dict()}455456 def get_metavar(self, param: Parameter, ctx: Context) -> str | None:457 return f"[{'|'.join(self.formats)}]"458
4 unmodified lines
463 return None464465 def convert(466 self, value: t.Any, param: Parameter | None, ctx: Context | None447 ) -> t.Any:467 ) -> datetime:468 if isinstance(value, datetime):469 return value470471 for format in self.formats:
16 unmodified lines
488 def __repr__(self) -> str:489 return "DateTime"490491472class _NumberParamTypeBase(ParamType):473 _number_class: t.ClassVar[type[t.Any]]492class _NumberParamTypeBase(ParamType[ParamTypeValue]):493 _number_class: t.Callable[[t.Any], ParamTypeValue]494495 def convert(496 self, value: t.Any, param: Parameter | None, ctx: Context | None477 ) -> t.Any:497 ) -> ParamTypeValue:498 try:499 return self._number_class(value)500 except ValueError:501 self.fail(
4 unmodified lines
506 ctx,507 )508509510class NumberRangeInfoDict(ParamTypeInfoDict):511 min: float | None512 max: float | None513 min_open: bool514 max_open: bool515 clamp: bool516517490class _NumberRangeBase(_NumberParamTypeBase):518class _NumberRangeBase(_NumberParamTypeBase[ParamTypeValue]):519 def __init__(520 self,521 min: float | None = None,522 max: float | None = None,
6 unmodified lines
529 self.min_open = min_open530 self.max_open = max_open531 self.clamp = clamp532505 def to_info_dict(self) -> dict[str, t.Any]:506 info_dict = super().to_info_dict()507 info_dict.update(508 min=self.min,509 max=self.max,510 min_open=self.min_open,511 max_open=self.max_open,512 clamp=self.clamp,513 )514 return info_dict533 def to_info_dict(self) -> NumberRangeInfoDict:534 return {535 "min": self.min,536 "max": self.max,537 "min_open": self.min_open,538 "max_open": self.max_open,539 "clamp": self.clamp,540 **super().to_info_dict(),541 }542543 def convert(544 self, value: t.Any, param: Parameter | None, ctx: Context | None518 ) -> t.Any:545 ) -> ParamTypeValue:546 import operator547548 rv = super().convert(value, param, ctx)549 min = self.min550 max = self.max522 lt_min: bool = self.min is not None and (551 lt_min: bool = min is not None and (552 operator.le if self.min_open else operator.lt524 )(rv, self.min)525 gt_max: bool = self.max is not None and (553 )(rv, min) # type: ignore[arg-type]554 gt_max: bool = max is not None and (555 operator.ge if self.max_open else operator.gt527 )(rv, self.max)556 )(rv, max) # type: ignore[arg-type]557558 if self.clamp:530 if lt_min:531 return self._clamp(self.min, 1, self.min_open) # type: ignore559 if min is not None and lt_min:560 return self._clamp(min, 1, self.min_open) # type: ignore[arg-type]561533 if gt_max:534 return self._clamp(self.max, -1, self.max_open) # type: ignore562 if max is not None and gt_max:563 return self._clamp(max, -1, self.max_open) # type: ignore[arg-type]564565 if lt_min or gt_max:566 self.fail(567 _("{value} is not in the range {range}.").format(
4 unmodified lines
572 )573574 return rv575547 def _clamp(self, bound: float, dir: t.Literal[1, -1], open: bool) -> float:576 @abc.abstractmethod577 def _clamp(578 self, bound: ParamTypeValue, dir: t.Literal[1, -1], open: bool579 ) -> ParamTypeValue:580 """Find the valid value to clamp to bound in the given581 direction.582583 :param bound: The boundary value.584 :param dir: 1 or -1 indicating the direction to move.585 :param open: If true, the range does not include the bound.586 """555 raise NotImplementedError587 ...588589 def _describe_range(self) -> str:590 """Describe the range for use in help text."""591 if self.min is None:
12 unmodified lines
604 clamp = " clamped" if self.clamp else ""605 return f"<{type(self).__name__} {self._describe_range()}{clamp}>"606607576class IntParamType(_NumberParamTypeBase):608class IntParamType(_NumberParamTypeBase[int]):609 name = "integer"610 _number_class = int611612 def __repr__(self) -> str:613 return "INT"614615584class IntRange(_NumberRangeBase, IntParamType):616class IntRange(_NumberRangeBase[int], IntParamType):617 """Restrict an :data:`click.INT` value to a range of accepted618 values. See :ref:`ranges`.619620 If ``min`` or ``max`` are not passed, any value is accepted in that
8 unmodified lines
629 """630631 name = "integer range"632601 def _clamp( # type: ignore602 self, bound: int, dir: t.Literal[1, -1], open: bool603 ) -> int:633 def _clamp(self, bound: int, dir: t.Literal[1, -1], open: bool) -> int:634 if not open:635 return bound636637 return bound + dir638639610class FloatParamType(_NumberParamTypeBase):640class FloatParamType(_NumberParamTypeBase[float]):641 name = "float"642 _number_class = float643644 def __repr__(self) -> str:645 return "FLOAT"646647618class FloatRange(_NumberRangeBase, FloatParamType):648class FloatRange(_NumberRangeBase[float], FloatParamType):649 """Restrict a :data:`click.FLOAT` value to a range of accepted650 values. See :ref:`ranges`.651652 If ``min`` or ``max`` are not passed, any value is accepted in that
34 unmodified lines
687 # left up to the user to write a callback to do it if needed.688 raise RuntimeError("Clamping is not supported for open bounds.")689690661class BoolParamType(ParamType):691class BoolParamType(ParamType[bool]):692 name = "boolean"693694 bool_states: dict[str, bool] = {695 "1": True,
60 unmodified lines
756 def __repr__(self) -> str:757 return "BOOL"758759730class UUIDParameterType(ParamType):760class UUIDParameterType(ParamType[uuid.UUID]):761 name = "uuid"762763 def convert(764 self, value: t.Any, param: Parameter | None, ctx: Context | None735 ) -> t.Any:736 import uuid737765 ) -> uuid.UUID:766 if isinstance(value, uuid.UUID):767 return value768769 value = value.strip()
8 unmodified lines
778 def __repr__(self) -> str:779 return "UUID"780781754class File(ParamType):782class FileInfoDict(ParamTypeInfoDict):783 mode: str784 encoding: str | None785786787class File(ParamType[t.IO[t.Any]]):788 """Declares a parameter to be a file for reading or writing. The file789 is automatically closed once the context tears down (after the command790 finished working).791
38 unmodified lines
830 self.errors = errors831 self.lazy = lazy832 self.atomic = atomic833801 def to_info_dict(self) -> dict[str, t.Any]:802 info_dict = super().to_info_dict()803 info_dict.update(mode=self.mode, encoding=self.encoding)804 return info_dict834 def to_info_dict(self) -> FileInfoDict:835 return {836 "mode": self.mode,837 "encoding": self.encoding,838 **super().to_info_dict(),839 }840841 def resolve_lazy_flag(self, value: str | os.PathLike[str]) -> bool:842 if self.lazy is not None:843 return self.lazy
66 unmodified lines
910def _is_file_like(value: t.Any) -> te.TypeGuard[t.IO[t.Any]]:911 return hasattr(value, "read") or hasattr(value, "write")912913879class Path(ParamType):914class PathInfoDict(ParamTypeInfoDict):915 exists: bool916 file_okay: bool917 dir_okay: bool918 writable: bool919 readable: bool920 allow_dash: bool921922923class Path(ParamType[str | bytes | os.PathLike[str]]):924 """The ``Path`` type is similar to the :class:`File` type, but925 returns the filename instead of an open file. Various checks can be926 enabled to validate the type of file and permissions.927
55 unmodified lines
983 self.name = _("directory")984 else:985 self.name = _("path")986943 def to_info_dict(self) -> dict[str, t.Any]:944 info_dict = super().to_info_dict()945 info_dict.update(946 exists=self.exists,947 file_okay=self.file_okay,948 dir_okay=self.dir_okay,949 writable=self.writable,950 readable=self.readable,951 allow_dash=self.allow_dash,952 )953 return info_dict987 def to_info_dict(self) -> PathInfoDict:988 return {989 "exists": self.exists,990 "file_okay": self.file_okay,991 "dir_okay": self.dir_okay,992 "writable": self.writable,993 "readable": self.readable,994 "allow_dash": self.allow_dash,995 **super().to_info_dict(),996 }997998 def coerce_path_result(999 self, value: str | os.PathLike[str]1000 ) -> str | bytes | os.PathLike[str]:
98 unmodified lines
1099 type = "dir" if self.dir_okay and not self.file_okay else "file"1100 return [CompletionItem(incomplete, type=type)]110111021060class Tuple(CompositeParamType):1103class TupleInfoDict(ParamTypeInfoDict):1104 types: cabc.Sequence[ParamTypeInfoDict]110511061107class Tuple(CompositeParamType[tuple[t.Any, ...]]):1108 """The default behavior of Click is to apply a type on a value directly.1109 This works well in most cases, except for when `nargs` is set to a fixed1110 count and different types should be used for different items. In this1111 case the :class:`Tuple` type can be used. This type can only be used
5 unmodified lines
11171118 :param types: a list of types that should be used for the tuple items.1119 """11201074 def __init__(self, types: cabc.Sequence[type[t.Any] | ParamType]) -> None:1075 self.types: cabc.Sequence[ParamType] = [convert_type(ty) for ty in types]1121 def __init__(self, types: cabc.Sequence[type[t.Any] | ParamType[t.Any]]) -> None:1122 self.types: cabc.Sequence[ParamType[t.Any]] = [convert_type(ty) for ty in types]11231077 def to_info_dict(self) -> dict[str, t.Any]:1078 info_dict = super().to_info_dict()1079 info_dict["types"] = [t.to_info_dict() for t in self.types]1080 return info_dict1124 def to_info_dict(self) -> TupleInfoDict:1125 return {1126 "types": [ty.to_info_dict() for ty in self.types],1127 **super().to_info_dict(),1128 }11291130 @property1083 def name(self) -> str: # type: ignore1131 def name(self) -> str: # type: ignore[override]1132 return f"<{' '.join(ty.name for ty in self.types)}>"11331134 @property1087 def arity(self) -> int: # type: ignore1135 def arity(self) -> int: # type: ignore[override]1136 return len(self.types)11371138 def convert(1139 self, value: t.Any, param: Parameter | None, ctx: Context | None1092 ) -> t.Any:1140 ) -> tuple[t.Any, ...]:1141 len_type = len(self.types)1142 len_value = len(value)11431144 if len_value != len_type:
11 unmodified lines
1156 ty(x, param, ctx) for ty, x in zip(self.types, value, strict=False)1157 )115811591112def convert_type(ty: t.Any | None, default: t.Any | None = None) -> ParamType:1160def convert_type(ty: t.Any | None, default: t.Any | None = None) -> ParamType[t.Any]:1161 """Find the most appropriate :class:`ParamType` for the given Python1162 type. If the type isn't provided, it can be inferred from a default1163 value.1164 """
59 unmodified lines
1224#: appear in bytes and unicode.1225#:1226#: For path related uses the :class:`Path` type is a better choice but1227#: there are situations where an unprocessed type is useful which is why1180#: it is is provided.1228#: it is provided.1229#:1230#: .. versionadded:: 4.01231UNPROCESSED = UnprocessedParamType()1232
25 unmodified lines
modified:tests/test_defaults.py+39 added-2 removed
82 unmodified lines
83 assert result.output.splitlines() == ["<1|2>", "<3|4>"]848586def test_multiple_flag_default(runner):87 """Default default for flags when multiple=True should be empty tuple."""87 """Default for flags when multiple=True should be empty tuple."""8889 @click.command90 # flag due to secondary token91 @click.option("-y/-n", multiple=True)
181 unmodified lines
273 subclass that falls back to prefix-based lookup when the parent returns274 ``None``.275276 Previous attempts in https://github.com/pallets/click/pr/3199 were entirely277 bypassing the user's overridded method.277 bypassing the user's overridden method.278 """279280 class CustomContext(click.Context):281 def lookup_default(self, name, call=True):
74 unmodified lines
356 assert result.exit_code == 0357 assert result.output == repr(expected)358359360@pytest.mark.parametrize(361 ("default_map", "option_kwargs", "cli_args", "expected"),362 [363 # String is split for nargs=2 option.364 ({"point": "3 4"}, {"nargs": 2, "type": int}, [], (3, 4)),365 # String is split for explicit Tuple type.366 ({"point": "hello world"}, {"type": (str, str)}, [], ("hello", "world")),367 # Already-structured tuple passes through unchanged.368 ({"point": ("a", "b")}, {"nargs": 2}, [], ("a", "b")),369 # Already-structured list passes through unchanged.370 ({"point": [5, 6]}, {"nargs": 2, "type": int}, [], (5, 6)),371 # CLI args override default_map for nargs > 1.372 (373 {"point": "3 4"},374 {"nargs": 2, "type": int},375 ["--point", "10", "20"],376 (10, 20),377 ),378 ],379)380def test_default_map_nargs(runner, default_map, option_kwargs, cli_args, expected):381 """A string in ``default_map`` for an option with ``nargs > 1`` should be382 split the same way an environment variable string is split.383384 Regression test for https://github.com/pallets/click/issues/2745.385 """386387 @click.command()388 @click.option("--point", **option_kwargs)389 def cli(point):390 click.echo(repr(point))391392 result = runner.invoke(cli, cli_args, default_map=default_map)393 assert result.exit_code == 0394 assert result.output.strip() == repr(expected)395396397def test_unset_in_default_map(runner):398 """An ``UNSET`` value in ``default_map`` should be treated as if399 the key is absent, and so fallback to the parameter's own default.400
13 unmodified lines
modified:tests/test_imports.py+2 added
25 unmodified lines
26"""2728ALLOWED_IMPORTS = {29 "__future__",30 "abc",31 "codecs",32 "collections",33 "collections.abc",34 "configparser",
14 unmodified lines
49 "sys",50 "threading",51 "types",52 "typing",53 "uuid",54 "weakref",55}5657if WIN:
23 unmodified lines
modified:tests/test_options.py+8 added-8 removed
518 unmodified lines
519@pytest.mark.parametrize(520 "value",521 (522 # Extra spaces inside the value.523 "tr ue",523 "tr ue", # codespell:ignore ue524 "fa lse",525 # Numbers.526 "10",527 "01",
470 unmodified lines
998 """a dumb override of a default value for testing"""999 return "I am a default"10001001 @click.command()1002 @click.argument("testarg", cls=CustomArgument, default="you wont see me")1002 @click.argument("testarg", cls=CustomArgument, default="you won't see me")1003 def cmd(testarg):1004 click.echo(testarg)10051006 result = runner.invoke(cmd)1007 assert "I am a default" in result.output1008 assert "you wont see me" not in result.output1008 assert "you won't see me" not in result.output100910101011def test_option_custom_class(runner):1012 class CustomOption(click.Option):
1 unmodified line
1014 """a dumb override of a help text for testing"""1015 return ("--help", "I am a help text")10161017 @click.command()1018 @click.option("--testoption", cls=CustomOption, help="you wont see me")1018 @click.option("--testoption", cls=CustomOption, help="you won't see me")1019 def cmd(testoption):1020 click.echo(testoption)10211022 result = runner.invoke(cmd, ["--help"])1023 assert "I am a help text" in result.output1024 assert "you wont see me" not in result.output1024 assert "you won't see me" not in result.output102510261027@pytest.mark.parametrize(1028 ("param_decl", "option_kwargs", "pass_argv"),
38 unmodified lines
1067 def get_help_record(self, ctx):1068 """a dumb override of a help text for testing"""1069 return ("--help", "I am a help text")10701071 # Assign to a variable to re-use the decorator.1072 testoption = click.option("--testoption", cls=CustomOption, help="you wont see me")1071 # Assign to a variable to reuse the decorator.1072 testoption = click.option("--testoption", cls=CustomOption, help="you won't see me")10731074 @click.command()1075 @testoption1076 def cmd1(testoption):
7 unmodified lines
1084 # Both of the commands should have the --help option now.1085 for cmd in (cmd1, cmd2):1086 result = runner.invoke(cmd, ["--help"])1087 assert "I am a help text" in result.output1088 assert "you wont see me" not in result.output1088 assert "you won't see me" not in result.output108910901091@pytest.mark.parametrize("custom_class", (True, False))1092@pytest.mark.parametrize(
1532 unmodified lines
modified:tests/test_termui.py+1 added-1 removed
394 unmodified lines
395396 result = click.edit(filename=named_tempfile.name, editor="sed -i~ 's/$/Test/'")397 assert result is None398399 # We need ot reopen the file as it becomes unreadable after the edit.399 # We need to reopen the file as it becomes unreadable after the edit.400 with open(named_tempfile.name) as reopened_file:401 # POSIX says that when sed writes a pattern space to output then it402 # is immediately followed by a newline and so the expected result403 # should contain the newline. However, some sed implementations
587 unmodified lines
modified:tests/test_types.py+1 added-1 removed
226 unmodified lines
227 path = tmp_path / "\udcff"228229 # - common case: �': No such file or directory230 # - special case: Illegal byte sequence231 # The spacial case is seen with rootless Podman. The root cause is most231 # The special case is seen with rootless Podman. The root cause is most232 # likely that the path is handled by a user-space program (FUSE).233 match = r"(�': No such file or directory|Illegal byte sequence)"234 with pytest.raises(click.BadParameter, match=match):235 type.convert(path, None, None)
22 unmodified lines
modified:.pre-commit-config.yaml+6 added-1 removed
1repos:2 - repo: https://github.com/astral-sh/ruff-pre-commit3 rev: c60c980e561ed3e73101667fe8365c609d19a438 # frozen: v0.15.94 hooks:5 - id: ruff5 - id: ruff-check6 - id: ruff-format7 - repo: https://github.com/astral-sh/uv-pre-commit8 rev: 0397b68f6f88c024f1d2b355a9818779f6336d16 # frozen: 0.11.39 hooks:10 - id: uv-lock11 - repo: https://github.com/codespell-project/codespell12 rev: 2ccb47ff45ad361a21071a7eedda4c37e6ae8c5a # frozen: v2.4.213 hooks:14 - id: codespell15 args: ['--write-changes', '--ignore-words-list=inout,te']16 - repo: https://github.com/pre-commit/pre-commit-hooks17 rev: 3e8a8703264a2f4a69428a0aa4dcb512790b2c8c # frozen: v6.0.018 hooks:19 - id: check-merge-conflict
5 unmodified lines
modified:CHANGES.rst+22 added-1 removed
29 unmodified lines
30-------------3132Unreleased3334- :class:`ParamType` typing improvements. :pr:`3371`3536 - :class:`ParamType` is now a generic abstract base class,37 parameterized by its converted value type.38 - :meth:`~ParamType.convert` return types are narrowed on all39 concrete types (``str`` for :class:`STRING`, ``int`` for40 :class:`INT`, etc.).41 - :meth:`~ParamType.to_info_dict` returns specific42 :class:`~typing.TypedDict` subclasses instead of43 ``dict[str, Any]``.44 - :class:`CompositeParamType` and the number-range base are now45 generic with abstract methods.46- Split string values from ``default_map`` for parameters with ``nargs > 1``47 or :class:`Tuple` type, matching environment variable behavior.48 :issue:`2745` :pr:`3364`4950Version 8.3.351-------------5253Released 2026-04-205455- Use :func:`shlex.split` to split pager and editor commands into ``argv``56 lists for :class:`subprocess.Popen`, removing ``shell=True``.57 :issue:`1026` :pr:`1477` :pr:`2775`58- Fix ``TypeError`` when rendering help for an option whose default value is
929 unmodified lines
988- ``_AtomicFile`` now uses the ``realpath`` of the original filename989 so that changing the working directory does not affect it. :pr:`920`990- Fix incorrect completions when defaults are present :issue:`925`,991 :pr:`930`971- Add copy option attrs so that custom classes can be re-used.992- Add copy option attrs so that custom classes can be reused.993 :issue:`926`, :pr:`994`994- "x" and "a" file modes now use stdout when file is ``"-"``.995 :pr:`929`996- Fix missing comma in ``__all__`` list. :pr:`935`
420 unmodified lines
modified:pyproject.toml+1 added-1 removed
1[project]2name = "click"3version = "8.3.2"3version = "8.3.3"4description = "Composable command line interface toolkit"5readme = "README.md"6license = "BSD-3-Clause"7license-files = ["LICENSE.txt"]
229 unmodified lines
modified:uv.lock+14 added-14 removed
171 unmodified lines
172]173174[[package]]175name = "click"176version = "8.3.2"176version = "8.3.3"177source = { editable = "." }178dependencies = [179 { name = "colorama", marker = "sys_platform == 'win32'" },180]
719 unmodified lines
900 { url = "https://files.pythonhosted.org/packages/3b/ab/b3226f0bd7cdcf710fbede2b3548584366da3b19b5021e74f5bde2a8fa3f/pytest-9.0.2-py3-none-any.whl", hash = "sha256:711ffd45bf766d5264d487b917733b453d917afd2b0ad65223959f59089f875b", size = 374801, upload-time = "2025-12-06T21:30:49.154Z" },901]902903[[package]]904name = "python-discovery"905version = "1.2.1"906source = { registry = "https://pypi.org/simple" }907dependencies = [908 { name = "filelock" },909 { name = "platformdirs" },910]911sdist = { url = "https://files.pythonhosted.org/packages/b9/88/815e53084c5079a59df912825a279f41dd2e0df82281770eadc732f5352c/python_discovery-1.2.1.tar.gz", hash = "sha256:180c4d114bff1c32462537eac5d6a332b768242b76b69c0259c7d14b1b680c9e", size = 58457, upload-time = "2026-03-26T22:30:44.496Z" }912wheels = [913 { url = "https://files.pythonhosted.org/packages/67/0f/019d3949a40280f6193b62bc010177d4ce702d0fce424322286488569cd3/python_discovery-1.2.1-py3-none-any.whl", hash = "sha256:b6a957b24c1cd79252484d3566d1b49527581d46e789aaf43181005e56201502", size = 31674, upload-time = "2026-03-26T22:30:43.396Z" },914]915916[[package]]904name = "pytest-randomly"905version = "4.0.1"906source = { registry = "https://pypi.org/simple" }907dependencies = [
17 unmodified lines
925 { url = "https://files.pythonhosted.org/packages/ca/31/d4e37e9e550c2b92a9cbc2e4d0b7420a27224968580b5a447f420847c975/pytest_xdist-3.8.0-py3-none-any.whl", hash = "sha256:202ca578cfeb7370784a8c33d6d05bc6e13b4f25b5053c30a152269fd10f0b88", size = 46396, upload-time = "2025-07-01T13:30:56.632Z" },926]927928[[package]]929name = "python-discovery"930version = "1.2.1"931source = { registry = "https://pypi.org/simple" }932dependencies = [933 { name = "filelock" },934 { name = "platformdirs" },935]936sdist = { url = "https://files.pythonhosted.org/packages/b9/88/815e53084c5079a59df912825a279f41dd2e0df82281770eadc732f5352c/python_discovery-1.2.1.tar.gz", hash = "sha256:180c4d114bff1c32462537eac5d6a332b768242b76b69c0259c7d14b1b680c9e", size = 58457, upload-time = "2026-03-26T22:30:44.496Z" }937wheels = [938 { url = "https://files.pythonhosted.org/packages/67/0f/019d3949a40280f6193b62bc010177d4ce702d0fce424322286488569cd3/python_discovery-1.2.1-py3-none-any.whl", hash = "sha256:b6a957b24c1cd79252484d3566d1b49527581d46e789aaf43181005e56201502", size = 31674, upload-time = "2026-03-26T22:30:43.396Z" },939]940941[[package]]942name = "pyyaml"943version = "6.0.3"944source = { registry = "https://pypi.org/simple" }945sdist = { url = "https://files.pythonhosted.org/packages/05/8e/961c0007c59b8dd7729d542c61a4d537767a59645b82a0b521206e1e25c2/pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f", size = 130960, upload-time = "2025-09-25T21:33:16.546Z" }
720 unmodified lines