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
Provenance
- Commit
5989375- Tree
1388a43- Author
Andreas Backx <AndreasBackx@users.noreply.github.com>- Committer
Kevin Deldycke <kevin@deldycke.com>- Parent
d777956
5 files changed+159 added−95 removed
modified:src/click/core.py+5 added-5 removed
2147 unmodified lines2148 2149 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 same23 unmodified lines2180 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)2185 2186 # Default nargs to what the type tells us if we have that2187 # information available.2188 if nargs is None:458 unmodified lines2647 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.2652 2653 :param ctx: Invocation context for this command.2654 :param incomplete: Value being completed. May be empty.2655 92 unmodified lines2748 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 lines2824 # 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 linesmodified:src/click/termui.py+2 added-2 removed
61 unmodified lines62 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 lines86 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 linesmodified:src/click/types.py+132 added-88 removed
1 from __future__ import annotations2 3+import abc4 import collections.abc as cabc5 import enum6 import os7 import stat8 import sys9 import typing as t10+import uuid11 from datetime import datetime12 from gettext import gettext as _13 from gettext import ngettext14 13 unmodified lines28 29 ParamTypeValue = t.TypeVar("ParamTypeValue")30 31 30-class ParamType:32+class ParamTypeInfoDict(t.TypedDict):33+ param_type: str34+ name: str35+36+37+class 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.40 41 To implement a custom type, subclass and implement at least the23 unmodified lines65 #: are split by ``os.path.pathsep`` by default (":" on Unix and ";" on66 #: Windows).67 envvar_list_splitter: t.ClassVar[str | None] = None68 62- 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.72 73 Use :meth:`click.Context.to_info_dict` to traverse the entire17 unmodified lines91 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 None99 100 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 lines108 """109 110 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).115 116 This must accept string values from the command line, as well as11 unmodified lines128 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]133 134 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 lines167 """168 return []169 170 163-class CompositeParamType(ParamType):171+class CompositeParamType(ParamType[ParamTypeValue]):172 is_composite = True173 174 @property167- def arity(self) -> int: # type: ignore168- raise NotImplementedError()175+ @abc.abstractmethod176+ def arity(self) -> int: ... # type: ignore[override]177 178 171-class FuncParamType(ParamType):179+class FuncParamTypeInfoDict(ParamTypeInfoDict):180+ func: t.Callable[[t.Any], t.Any]181+182+183+class 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 = func187 176- 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()}190 191 def convert(192 self, value: t.Any, param: Parameter | None, ctx: Context | None193 ) -> t.Any:7 unmodified lines201 202 self.fail(value, param, ctx)203 204 195-class UnprocessedParamType(ParamType):205+class UnprocessedParamType(ParamType[t.Any]):206 name = "text"207 208 def convert(209 self, value: t.Any, param: Parameter | None, ctx: Context | None3 unmodified lines213 def __repr__(self) -> str:214 return "UNPROCESSED"215 216 207-class StringParamType(ParamType):217+class StringParamType(ParamType[str]):218 name = "text"219 220 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 lines232 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)238 239 def __repr__(self) -> str:240 return "STRING"241 242 233-class Choice(ParamType, t.Generic[ParamTypeValue]):243+class ChoiceInfoDict(ParamTypeInfoDict):244+ choices: cabc.Sequence[t.Any]245+ case_sensitive: bool246+247+248+class Choice(ParamType[ParamTypeValue], t.Generic[ParamTypeValue]):249 """The choice type allows a value to be checked against a fixed set250 of supported values.251 252 You may pass any iterable value which will be converted to a tuple22 unmodified lines275 ) -> None:276 self.choices: cabc.Sequence[ParamTypeValue] = tuple(choices)277 self.case_sensitive = case_sensitive278 264- 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+ }285 286 def _normalized_mapping(287 self, ctx: Context | None = None288 ) -> cabc.Mapping[ParamTypeValue, str]:124 unmodified lines413 414 return [CompletionItem(c) for c in matched]415 416 401-class DateTime(ParamType):417+class DateTimeInfoDict(ParamTypeInfoDict):418+ formats: cabc.Sequence[str]419+420+421+class DateTime(ParamType[datetime]):422 """The DateTime type converts date strings into `datetime` objects.423 424 The format strings which are checked are configurable, but default to some425 common (non-timezone aware) ISO 8601 formats.21 unmodified lines447 "%Y-%m-%dT%H:%M:%S",448 "%Y-%m-%d %H:%M:%S",449 ]450 431- 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()}453 454 def get_metavar(self, param: Parameter, ctx: Context) -> str | None:455 return f"[{'|'.join(self.formats)}]"456 4 unmodified lines461 return None462 463 def convert(464 self, value: t.Any, param: Parameter | None, ctx: Context | None447- ) -> t.Any:465+ ) -> datetime:466 if isinstance(value, datetime):467 return value468 469 for format in self.formats:16 unmodified lines486 def __repr__(self) -> str:487 return "DateTime"488 489 472-class _NumberParamTypeBase(ParamType):473- _number_class: t.ClassVar[type[t.Any]]490+class _NumberParamTypeBase(ParamType[ParamTypeValue]):491+ _number_class: t.Callable[[t.Any], ParamTypeValue]492 493 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 lines504 ctx,505 )506 507 508+class NumberRangeInfoDict(ParamTypeInfoDict):509+ min: float | None510+ max: float | None511+ min_open: bool512+ max_open: bool513+ clamp: bool514+515+490-class _NumberRangeBase(_NumberParamTypeBase):516+class _NumberRangeBase(_NumberParamTypeBase[ParamTypeValue]):517 def __init__(518 self,519 min: float | None = None,520 max: float | None = None,6 unmodified lines527 self.min_open = min_open528 self.max_open = max_open529 self.clamp = clamp530 505- 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+ }540 541 def convert(542 self, value: t.Any, param: Parameter | None, ctx: Context | None518- ) -> t.Any:543+ ) -> ParamTypeValue:544 import operator545 546 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]553 554 if self.clamp:555 if lt_min:556 return self._clamp(self.min, 1, self.min_open) # type: ignore11 unmodified lines568 )569 570 return rv571 547- 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.578 579 :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+ ...584 585 def _describe_range(self) -> str:586 """Describe the range for use in help text."""587 if self.min is None:12 unmodified lines600 clamp = " clamped" if self.clamp else ""601 return f"<{type(self).__name__} {self._describe_range()}{clamp}>"602 603 576-class IntParamType(_NumberParamTypeBase):604+class IntParamType(_NumberParamTypeBase[int]):605 name = "integer"606 _number_class = int607 608 def __repr__(self) -> str:609 return "INT"610 611 584-class IntRange(_NumberRangeBase, IntParamType):612+class IntRange(_NumberRangeBase[int], IntParamType):613 """Restrict an :data:`click.INT` value to a range of accepted614 values. See :ref:`ranges`.615 616 If ``min`` or ``max`` are not passed, any value is accepted in that8 unmodified lines625 """626 627 name = "integer range"628 601- 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 bound632 633 return bound + dir634 635 610-class FloatParamType(_NumberParamTypeBase):636+class FloatParamType(_NumberParamTypeBase[float]):637 name = "float"638 _number_class = float639 640 def __repr__(self) -> str:641 return "FLOAT"642 643 618-class FloatRange(_NumberRangeBase, FloatParamType):644+class FloatRange(_NumberRangeBase[float], FloatParamType):645 """Restrict a :data:`click.FLOAT` value to a range of accepted646 values. See :ref:`ranges`.647 648 If ``min`` or ``max`` are not passed, any value is accepted in that34 unmodified lines683 # left up to the user to write a callback to do it if needed.684 raise RuntimeError("Clamping is not supported for open bounds.")685 686 661-class BoolParamType(ParamType):687+class BoolParamType(ParamType[bool]):688 name = "boolean"689 690 bool_states: dict[str, bool] = {691 "1": True,60 unmodified lines752 def __repr__(self) -> str:753 return "BOOL"754 755 730-class UUIDParameterType(ParamType):756+class UUIDParameterType(ParamType[uuid.UUID]):757 name = "uuid"758 759 def convert(760 self, value: t.Any, param: Parameter | None, ctx: Context | None735- ) -> t.Any:736- import uuid737-761+ ) -> uuid.UUID:762 if isinstance(value, uuid.UUID):763 return value764 765 value = value.strip()8 unmodified lines774 def __repr__(self) -> str:775 return "UUID"776 777 754-class File(ParamType):778+class FileInfoDict(ParamTypeInfoDict):779+ mode: str780+ encoding: str | None781+782+783+class 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 lines826 self.errors = errors827 self.lazy = lazy828 self.atomic = atomic829 801- 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+ }836 837 def resolve_lazy_flag(self, value: str | os.PathLike[str]) -> bool:838 if self.lazy is not None:839 return self.lazy66 unmodified lines906 def _is_file_like(value: t.Any) -> te.TypeGuard[t.IO[t.Any]]:907 return hasattr(value, "read") or hasattr(value, "write")908 909 879-class Path(ParamType):910+class PathInfoDict(ParamTypeInfoDict):911+ exists: bool912+ file_okay: bool913+ dir_okay: bool914+ writable: bool915+ readable: bool916+ allow_dash: bool917+918+919+class 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 lines979 self.name = _("directory")980 else:981 self.name = _("path")982 943- 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+ }993 994 def coerce_path_result(995 self, value: str | os.PathLike[str]996 ) -> str | bytes | os.PathLike[str]:98 unmodified lines1095 type = "dir" if self.dir_okay and not self.file_okay else "file"1096 return [CompletionItem(incomplete, type=type)]1097 1098 1060-class Tuple(CompositeParamType):1099+class TupleInfoDict(ParamTypeInfoDict):1100+ types: cabc.Sequence[ParamTypeInfoDict]1101+1102+1103+class 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 used5 unmodified lines1113 1114 :param types: a list of types that should be used for the tuple items.1115 """1116 1074- 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]1119 1077- 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+ }1125 1126 @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)}>"1129 1130 @property1087- def arity(self) -> int: # type: ignore1131+ def arity(self) -> int: # type: ignore[override]1132 return len(self.types)1133 1134 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)1139 1140 if len_value != len_type:11 unmodified lines1152 ty(x, param, ctx) for ty, x in zip(self.types, value, strict=False)1153 )1154 1155 1112-def convert_type(ty: t.Any | None, default: t.Any | None = None) -> ParamType:1156+def 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 linesmodified:tests/test_imports.py+2 added
25 unmodified lines26 """27 28 ALLOWED_IMPORTS = {29 "__future__",30+ "abc",31 "codecs",32 "collections",33 "collections.abc",34 "configparser",14 unmodified lines49 "sys",50 "threading",51 "types",52 "typing",53+ "uuid",54 "weakref",55 }56 57 if WIN:23 unmodified linesmodified:CHANGES.rst+18 added
1 .. currentmodule:: click2 3+Version 8.4.04+-------------5+6+Unreleased7+8+- :class:`ParamType` typing improvements. :pr:`3371`9+10+ - :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.20+21 Version 8.3.322 -------------23 24 Released 2026-04-201363 unmodified lines