Skip to content
Myr

ParamType typing improvements

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

authored by Andreas Backx · committed by Kevin Deldycke · parent d777956 · Browse files · 5 files+159 added−95 removed
This commit

State

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

Trailers

  • Co-authored-by: Kevin Deldycke <kevin@deldycke.com>

Diff stats

5 files+159 added−95 removed

  • tests:+2 added−0 removed
  • other:+157 added−95 removed

5 files+159 added−95 removed

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:
458 unmodified lines
2647 def shell_complete(self, ctx: Context, incomplete: str) -> list[CompletionItem]:2648 """Return a list of completions for the incomplete value. If a2649 ``shell_complete`` function was given during init, it is used.2650 Otherwise, the :attr:`type`2651 :meth:`~click.types.ParamType.shell_complete` function is used.2651 :meth:`~click.types.ParamType[t.Any].shell_complete` function is used.26522653 :param ctx: Invocation context for this command.2654 :param incomplete: Value being completed. May be empty.2655
92 unmodified lines
2748 flag_value: t.Any = UNSET,2749 multiple: bool = False,2750 count: bool = False,2751 allow_from_autoenv: bool = True,2752 type: types.ParamType | t.Any | None = None,2752 type: types.ParamType[t.Any] | t.Any | None = None,2753 help: str | None = None,2754 hidden: bool = False,2755 show_choices: bool = True,2756 show_envvar: bool = False,
67 unmodified lines
2824 # Auto-detect the type of the flag based on the flag_value.2825 if type is None:2826 # A flag without a flag_value is a boolean flag.2827 if flag_value is UNSET:2828 self.type: types.ParamType = types.BoolParamType()2828 self.type: types.ParamType[t.Any] = types.BoolParamType()2829 # If the flag value is a boolean, use BoolParamType.2830 elif isinstance(flag_value, bool):2831 self.type = types.BoolParamType()2832 # 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+132 added-88 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 return value # type: ignore[no-any-return]133134 def split_envvar_value(self, rv: str) -> cabc.Sequence[str]:135 """Given a value from an environment variable this splits it up136 into small chunks depending on the defined envvar list splitter.
30 unmodified lines
167 """168 return []169170163class CompositeParamType(ParamType):171class CompositeParamType(ParamType[ParamTypeValue]):172 is_composite = True173174 @property167 def arity(self) -> int: # type: ignore168 raise NotImplementedError()175 @abc.abstractmethod176 def arity(self) -> int: ... # type: ignore[override]177178171class FuncParamType(ParamType):179class FuncParamTypeInfoDict(ParamTypeInfoDict):180 func: t.Callable[[t.Any], t.Any]181182183class FuncParamType(ParamType[t.Any]):184 def __init__(self, func: t.Callable[[t.Any], t.Any]) -> None:185 self.name: str = func.__name__186 self.func = func187176 def to_info_dict(self) -> dict[str, t.Any]:177 info_dict = super().to_info_dict()178 info_dict["func"] = self.func179 return info_dict188 def to_info_dict(self) -> FuncParamTypeInfoDict:189 return {"func": self.func, **super().to_info_dict()}190191 def convert(192 self, value: t.Any, param: Parameter | None, ctx: Context | None193 ) -> t.Any:
7 unmodified lines
201202 self.fail(value, param, ctx)203204195class UnprocessedParamType(ParamType):205class UnprocessedParamType(ParamType[t.Any]):206 name = "text"207208 def convert(209 self, value: t.Any, param: Parameter | None, ctx: Context | None
3 unmodified lines
213 def __repr__(self) -> str:214 return "UNPROCESSED"215216207class StringParamType(ParamType):217class StringParamType(ParamType[str]):218 name = "text"219220 def convert(221 self, value: t.Any, param: Parameter | None, ctx: Context | None212 ) -> t.Any:222 ) -> str:223 if isinstance(value, bytes):224 enc = _get_argv_encoding()225 try:226 value = value.decode(enc)
5 unmodified lines
232 except UnicodeError:233 value = value.decode("utf-8", "replace")234 else:235 value = value.decode("utf-8", "replace")226 return value236 return value # type: ignore[no-any-return]237 return str(value)238239 def __repr__(self) -> str:240 return "STRING"241242233class Choice(ParamType, t.Generic[ParamTypeValue]):243class ChoiceInfoDict(ParamTypeInfoDict):244 choices: cabc.Sequence[t.Any]245 case_sensitive: bool246247248class Choice(ParamType[ParamTypeValue], t.Generic[ParamTypeValue]):249 """The choice type allows a value to be checked against a fixed set250 of supported values.251252 You may pass any iterable value which will be converted to a tuple
22 unmodified lines
275 ) -> None:276 self.choices: cabc.Sequence[ParamTypeValue] = tuple(choices)277 self.case_sensitive = case_sensitive278264 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_dict279 def to_info_dict(self) -> ChoiceInfoDict:280 return {281 "choices": self.choices,282 "case_sensitive": self.case_sensitive,283 **super().to_info_dict(),284 }285286 def _normalized_mapping(287 self, ctx: Context | None = None288 ) -> cabc.Mapping[ParamTypeValue, str]:
124 unmodified lines
413414 return [CompletionItem(c) for c in matched]415416401class DateTime(ParamType):417class DateTimeInfoDict(ParamTypeInfoDict):418 formats: cabc.Sequence[str]419420421class DateTime(ParamType[datetime]):422 """The DateTime type converts date strings into `datetime` objects.423424 The format strings which are checked are configurable, but default to some425 common (non-timezone aware) ISO 8601 formats.
21 unmodified lines
447 "%Y-%m-%dT%H:%M:%S",448 "%Y-%m-%d %H:%M:%S",449 ]450431 def to_info_dict(self) -> dict[str, t.Any]:432 info_dict = super().to_info_dict()433 info_dict["formats"] = self.formats434 return info_dict451 def to_info_dict(self) -> DateTimeInfoDict:452 return {"formats": self.formats, **super().to_info_dict()}453454 def get_metavar(self, param: Parameter, ctx: Context) -> str | None:455 return f"[{'|'.join(self.formats)}]"456
4 unmodified lines
461 return None462463 def convert(464 self, value: t.Any, param: Parameter | None, ctx: Context | None447 ) -> t.Any:465 ) -> datetime:466 if isinstance(value, datetime):467 return value468469 for format in self.formats:
16 unmodified lines
486 def __repr__(self) -> str:487 return "DateTime"488489472class _NumberParamTypeBase(ParamType):473 _number_class: t.ClassVar[type[t.Any]]490class _NumberParamTypeBase(ParamType[ParamTypeValue]):491 _number_class: t.Callable[[t.Any], ParamTypeValue]492493 def convert(494 self, value: t.Any, param: Parameter | None, ctx: Context | None477 ) -> t.Any:495 ) -> ParamTypeValue:496 try:497 return self._number_class(value)498 except ValueError:499 self.fail(
4 unmodified lines
504 ctx,505 )506507508class NumberRangeInfoDict(ParamTypeInfoDict):509 min: float | None510 max: float | None511 min_open: bool512 max_open: bool513 clamp: bool514515490class _NumberRangeBase(_NumberParamTypeBase):516class _NumberRangeBase(_NumberParamTypeBase[ParamTypeValue]):517 def __init__(518 self,519 min: float | None = None,520 max: float | None = None,
6 unmodified lines
527 self.min_open = min_open528 self.max_open = max_open529 self.clamp = clamp530505 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_dict531 def to_info_dict(self) -> NumberRangeInfoDict:532 return {533 "min": self.min,534 "max": self.max,535 "min_open": self.min_open,536 "max_open": self.max_open,537 "clamp": self.clamp,538 **super().to_info_dict(),539 }540541 def convert(542 self, value: t.Any, param: Parameter | None, ctx: Context | None518 ) -> t.Any:543 ) -> ParamTypeValue:544 import operator545546 rv = super().convert(value, param, ctx)547 lt_min: bool = self.min is not None and (548 operator.le if self.min_open else operator.lt524 )(rv, self.min)549 )(rv, self.min) # type: ignore[arg-type]550 gt_max: bool = self.max is not None and (551 operator.ge if self.max_open else operator.gt527 )(rv, self.max)552 )(rv, self.max) # type: ignore[arg-type]553554 if self.clamp:555 if lt_min:556 return self._clamp(self.min, 1, self.min_open) # type: ignore
11 unmodified lines
568 )569570 return rv571547 def _clamp(self, bound: float, dir: t.Literal[1, -1], open: bool) -> float:572 @abc.abstractmethod573 def _clamp(574 self, bound: ParamTypeValue, dir: t.Literal[1, -1], open: bool575 ) -> ParamTypeValue:576 """Find the valid value to clamp to bound in the given577 direction.578579 :param bound: The boundary value.580 :param dir: 1 or -1 indicating the direction to move.581 :param open: If true, the range does not include the bound.582 """555 raise NotImplementedError583 ...584585 def _describe_range(self) -> str:586 """Describe the range for use in help text."""587 if self.min is None:
12 unmodified lines
600 clamp = " clamped" if self.clamp else ""601 return f"<{type(self).__name__} {self._describe_range()}{clamp}>"602603576class IntParamType(_NumberParamTypeBase):604class IntParamType(_NumberParamTypeBase[int]):605 name = "integer"606 _number_class = int607608 def __repr__(self) -> str:609 return "INT"610611584class IntRange(_NumberRangeBase, IntParamType):612class IntRange(_NumberRangeBase[int], IntParamType):613 """Restrict an :data:`click.INT` value to a range of accepted614 values. See :ref:`ranges`.615616 If ``min`` or ``max`` are not passed, any value is accepted in that
8 unmodified lines
625 """626627 name = "integer range"628601 def _clamp( # type: ignore602 self, bound: int, dir: t.Literal[1, -1], open: bool603 ) -> int:629 def _clamp(self, bound: int, dir: t.Literal[1, -1], open: bool) -> int:630 if not open:631 return bound632633 return bound + dir634635610class FloatParamType(_NumberParamTypeBase):636class FloatParamType(_NumberParamTypeBase[float]):637 name = "float"638 _number_class = float639640 def __repr__(self) -> str:641 return "FLOAT"642643618class FloatRange(_NumberRangeBase, FloatParamType):644class FloatRange(_NumberRangeBase[float], FloatParamType):645 """Restrict a :data:`click.FLOAT` value to a range of accepted646 values. See :ref:`ranges`.647648 If ``min`` or ``max`` are not passed, any value is accepted in that
34 unmodified lines
683 # left up to the user to write a callback to do it if needed.684 raise RuntimeError("Clamping is not supported for open bounds.")685686661class BoolParamType(ParamType):687class BoolParamType(ParamType[bool]):688 name = "boolean"689690 bool_states: dict[str, bool] = {691 "1": True,
60 unmodified lines
752 def __repr__(self) -> str:753 return "BOOL"754755730class UUIDParameterType(ParamType):756class UUIDParameterType(ParamType[uuid.UUID]):757 name = "uuid"758759 def convert(760 self, value: t.Any, param: Parameter | None, ctx: Context | None735 ) -> t.Any:736 import uuid737761 ) -> uuid.UUID:762 if isinstance(value, uuid.UUID):763 return value764765 value = value.strip()
8 unmodified lines
774 def __repr__(self) -> str:775 return "UUID"776777754class File(ParamType):778class FileInfoDict(ParamTypeInfoDict):779 mode: str780 encoding: str | None781782783class File(ParamType[t.IO[t.Any]]):784 """Declares a parameter to be a file for reading or writing. The file785 is automatically closed once the context tears down (after the command786 finished working).787
38 unmodified lines
826 self.errors = errors827 self.lazy = lazy828 self.atomic = atomic829801 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_dict830 def to_info_dict(self) -> FileInfoDict:831 return {832 "mode": self.mode,833 "encoding": self.encoding,834 **super().to_info_dict(),835 }836837 def resolve_lazy_flag(self, value: str | os.PathLike[str]) -> bool:838 if self.lazy is not None:839 return self.lazy
66 unmodified lines
906def _is_file_like(value: t.Any) -> te.TypeGuard[t.IO[t.Any]]:907 return hasattr(value, "read") or hasattr(value, "write")908909879class Path(ParamType):910class PathInfoDict(ParamTypeInfoDict):911 exists: bool912 file_okay: bool913 dir_okay: bool914 writable: bool915 readable: bool916 allow_dash: bool917918919class Path(ParamType[str | bytes | os.PathLike[str]]):920 """The ``Path`` type is similar to the :class:`File` type, but921 returns the filename instead of an open file. Various checks can be922 enabled to validate the type of file and permissions.923
55 unmodified lines
979 self.name = _("directory")980 else:981 self.name = _("path")982943 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_dict983 def to_info_dict(self) -> PathInfoDict:984 return {985 "exists": self.exists,986 "file_okay": self.file_okay,987 "dir_okay": self.dir_okay,988 "writable": self.writable,989 "readable": self.readable,990 "allow_dash": self.allow_dash,991 **super().to_info_dict(),992 }993994 def coerce_path_result(995 self, value: str | os.PathLike[str]996 ) -> str | bytes | os.PathLike[str]:
98 unmodified lines
1095 type = "dir" if self.dir_okay and not self.file_okay else "file"1096 return [CompletionItem(incomplete, type=type)]109710981060class Tuple(CompositeParamType):1099class TupleInfoDict(ParamTypeInfoDict):1100 types: cabc.Sequence[ParamTypeInfoDict]110111021103class Tuple(CompositeParamType[tuple[t.Any, ...]]):1104 """The default behavior of Click is to apply a type on a value directly.1105 This works well in most cases, except for when `nargs` is set to a fixed1106 count and different types should be used for different items. In this1107 case the :class:`Tuple` type can be used. This type can only be used
5 unmodified lines
11131114 :param types: a list of types that should be used for the tuple items.1115 """11161074 def __init__(self, types: cabc.Sequence[type[t.Any] | ParamType]) -> None:1075 self.types: cabc.Sequence[ParamType] = [convert_type(ty) for ty in types]1117 def __init__(self, types: cabc.Sequence[type[t.Any] | ParamType[t.Any]]) -> None:1118 self.types: cabc.Sequence[ParamType[t.Any]] = [convert_type(ty) for ty in types]11191077 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_dict1120 def to_info_dict(self) -> TupleInfoDict:1121 return {1122 "types": [ty.to_info_dict() for ty in self.types],1123 **super().to_info_dict(),1124 }11251126 @property1083 def name(self) -> str: # type: ignore1127 def name(self) -> str: # type: ignore[override]1128 return f"<{' '.join(ty.name for ty in self.types)}>"11291130 @property1087 def arity(self) -> int: # type: ignore1131 def arity(self) -> int: # type: ignore[override]1132 return len(self.types)11331134 def convert(1135 self, value: t.Any, param: Parameter | None, ctx: Context | None1092 ) -> t.Any:1136 ) -> tuple[t.Any, ...]:1137 len_type = len(self.types)1138 len_value = len(value)11391140 if len_value != len_type:
11 unmodified lines
1152 ty(x, param, ctx) for ty, x in zip(self.types, value, strict=False)1153 )115411551112def convert_type(ty: t.Any | None, default: t.Any | None = None) -> ParamType:1156def convert_type(ty: t.Any | None, default: t.Any | None = None) -> ParamType[t.Any]:1157 """Find the most appropriate :class:`ParamType` for the given Python1158 type. If the type isn't provided, it can be inferred from a default1159 value.1160 """
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
modified:CHANGES.rst+18 added
1.. currentmodule:: click23Version 8.4.04-------------56Unreleased78- :class:`ParamType` typing improvements. :pr:`3371`910 - :class:`ParamType` is now a generic abstract base class,11 parameterized by its converted value type.12 - :meth:`~ParamType.convert` return types are narrowed on all13 concrete types (``str`` for :class:`STRING`, ``int`` for14 :class:`INT`, etc.).15 - :meth:`~ParamType.to_info_dict` returns specific16 :class:`~typing.TypedDict` subclasses instead of17 ``dict[str, Any]``.18 - :class:`CompositeParamType` and the number-range base are now19 generic with abstract methods.2021Version 8.3.322-------------2324Released 2026-04-20
1363 unmodified lines