Skip to content
Myr

Merge branch 'main' into fix-default-map-nargs

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

authored by Rowlando13 · committed by GitHub · parents 94004f1, 8a2b489 · Browse files · 9 files+205 added−113 removed
This commit

State

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

Diff stats

9 files+205 added−113 removed

  • tests:+2 added−0 removed
  • other:+203 added−113 removed

9 files+205 added−113 removed

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/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+5 added-5 removed
2147 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:
463 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`2656 :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
92 unmodified lines
2753 flag_value: t.Any = UNSET,2754 multiple: bool = False,2755 count: bool = False,2756 allow_from_autoenv: bool = True,2757 type: types.ParamType | t.Any | None = None,2757 type: types.ParamType[t.Any] | t.Any | None = None,2758 help: str | None = None,2759 hidden: bool = False,2760 show_choices: bool = True,2761 show_envvar: bool = False,
67 unmodified lines
2829 # Auto-detect the type of the flag based on the flag_value.2830 if type is None:2831 # A flag without a flag_value is a boolean flag.2832 if flag_value is UNSET:2833 self.type: types.ParamType = types.BoolParamType()2833 self.type: types.ParamType[t.Any] = types.BoolParamType()2834 # If the flag value is a boolean, use BoolParamType.2835 elif isinstance(flag_value, bool):2836 self.type = types.BoolParamType()2837 # Otherwise, guess the type from the flag value.
644 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+144 added-96 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 """
93 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