`ParamType` and other typing improvements (#3371)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Rowlando13 · committed by GitHub · parents 30a7f7c, ded5b69 · Browse files · 9 files·+196 added−109 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+196 added−109 removed
- tests:+2 added−0 removed
- other:+194 added−109 removed
Provenance
- Commit
8a2b489- Tree
005d805- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
30a7f7c- Parent 2
ded5b69
9 files changed+196 added−109 removed
modified:docs/parameter-types.md+21 added-2 removed
68 unmodified lines697071727374757677787980818275 unmodified lines1581591601611621631641651661671681691701711721621731741751651761771781791804 unmodified lines18518618718818919019119219319419519619719819920020120220320420568 unmodified linesThe resulting value from an option will always be one of the originally passed choicesregardless of `case_sensitive`.```
```{versionchanged} 8.4.0{class}`Choice` is now generic. Parameterize it with the choice value type({class}`!Choice[HashType]` for an enum, {class}`!Choice[str]` for plainstrings) to enable type-checked consumers.```
(ranges)=
### Int and Float Ranges
75 unmodified linesTo implement a custom type, you need to subclass the {class}`ParamType` class. For simple cases, passing a Pythonfunction that fails with a `ValueError` is also supported, though discouraged. Override the {meth}`~ParamType.convert`method to convert the value from a string to the correct type.
{class}`ParamType` is generic in the converted value type: parameterize it withthe type returned by `convert` so that consumers (and type checkers) can relyon the narrowed return type.
The following code implements an integer type that accepts hex and octal numbers in addition to normal integers, andconverts them into regular integers.
```pythonimport click
class BasedIntParamType(click.ParamType):class BasedIntParamType(click.ParamType[int]): name = "integer"
def convert(self, value, param, ctx): def convert(self, value, param, ctx) -> int: if isinstance(value, int): return value
try:4 unmodified lines return int(value, 10) except ValueError: self.fail(f"{value!r} is not a valid integer", param, ctx)
BASED_INT = BasedIntParamType()```
The {attr}`~ParamType.name` attribute is optional and is used for documentation. Call {meth}`~ParamType.fail` ifconversion fails. The `param` and `ctx` arguments may be `None` in some cases such as prompts.
Values from user input or the command line will be strings, but default values and Python arguments may already be thecorrect type. The custom type should check at the top if the value is already valid and pass it through to support thosecases.
```{versionchanged} 8.4.0{class}`ParamType` is now a generic abstract base class. Parameterize it withthe converted value type ({class}`!ParamType[int]` for an integer-returningtype) so that {meth}`~ParamType.convert` and downstream consumers carry thenarrowed type.```modified:docs/shell-completion.md+1 added-1 removed
118 unmodified lines119 120 In this example, the type will suggest environment variables that start with the incomplete value.121 122 ```python123-class EnvVarType(ParamType):123+class EnvVarType(ParamType[str]):124 name = "envvar"125 126 def shell_complete(self, ctx, param, incomplete):127 return [122 unmodified linesmodified:docs/support-multiple-versions.md+1 added-1 removed
53 unmodified lines54 55 Here's an example ``ParamType`` subclass which uses this:56 57 ```python58-class CommaDelimitedString(click.ParamType):58+class CommaDelimitedString(click.ParamType[str]):59 @add_ctx_arg60 def get_metavar(self, param: click.Parameter, ctx: click.Context | None) -> str:61 return "TEXT,TEXT,..."62 ```modified:examples/validation/validation.py+2 added-2 removed
7 unmodified lines8 raise click.BadParameter("Should be a positive, even integer.")9 return value10 11 12-class URL(click.ParamType):12+class URL(click.ParamType[urlparse.ParseResult]):13 name = "url"14 15- 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 linesmodified: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+144 added-96 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+ # 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)135 136 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 lines169 """170 return []171 172 163-class CompositeParamType(ParamType):173+class CompositeParamType(ParamType[ParamTypeValue]):174 is_composite = True175 176 @property167- def arity(self) -> int: # type: ignore168- raise NotImplementedError()177+ @abc.abstractmethod178+ def arity(self) -> int: ... # type: ignore[override]179 180 171-class FuncParamType(ParamType):172- def __init__(self, func: t.Callable[[t.Any], t.Any]) -> None:181+class FuncParamTypeInfoDict(ParamTypeInfoDict):182+ func: t.Callable[[t.Any], t.Any]183+184+185+class FuncParamType(ParamType[ParamTypeValue]):186+ def __init__(self, func: t.Callable[[t.Any], ParamTypeValue]) -> None:187 self.name: str = func.__name__188 self.func = func189 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_dict190+ def to_info_dict(self) -> FuncParamTypeInfoDict:191+ return {"func": self.func, **super().to_info_dict()}192 193 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 lines203 204 self.fail(value, param, ctx)205 206 195-class UnprocessedParamType(ParamType):207+class UnprocessedParamType(ParamType[t.Any]):208 name = "text"209 210 def convert(211 self, value: t.Any, param: Parameter | None, ctx: Context | None3 unmodified lines215 def __repr__(self) -> str:216 return "UNPROCESSED"217 218 207-class StringParamType(ParamType):219+class StringParamType(ParamType[str]):220 name = "text"221 222 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 lines234 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)240 241 def __repr__(self) -> str:242 return "STRING"243 244 233-class Choice(ParamType, t.Generic[ParamTypeValue]):245+class ChoiceInfoDict(ParamTypeInfoDict):246+ choices: cabc.Sequence[t.Any]247+ case_sensitive: bool248+249+250+class Choice(ParamType[ParamTypeValue], t.Generic[ParamTypeValue]):251 """The choice type allows a value to be checked against a fixed set252 of supported values.253 254 You may pass any iterable value which will be converted to a tuple22 unmodified lines277 ) -> None:278 self.choices: cabc.Sequence[ParamTypeValue] = tuple(choices)279 self.case_sensitive = case_sensitive280 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_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+ }287 288 def _normalized_mapping(289 self, ctx: Context | None = None290 ) -> cabc.Mapping[ParamTypeValue, str]:124 unmodified lines415 416 return [CompletionItem(c) for c in matched]417 418 401-class DateTime(ParamType):419+class DateTimeInfoDict(ParamTypeInfoDict):420+ formats: cabc.Sequence[str]421+422+423+class DateTime(ParamType[datetime]):424 """The DateTime type converts date strings into `datetime` objects.425 426 The format strings which are checked are configurable, but default to some427 common (non-timezone aware) ISO 8601 formats.21 unmodified lines449 "%Y-%m-%dT%H:%M:%S",450 "%Y-%m-%d %H:%M:%S",451 ]452 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_dict453+ def to_info_dict(self) -> DateTimeInfoDict:454+ return {"formats": self.formats, **super().to_info_dict()}455 456 def get_metavar(self, param: Parameter, ctx: Context) -> str | None:457 return f"[{'|'.join(self.formats)}]"458 4 unmodified lines463 return None464 465 def convert(466 self, value: t.Any, param: Parameter | None, ctx: Context | None447- ) -> t.Any:467+ ) -> datetime:468 if isinstance(value, datetime):469 return value470 471 for format in self.formats:16 unmodified lines488 def __repr__(self) -> str:489 return "DateTime"490 491 472-class _NumberParamTypeBase(ParamType):473- _number_class: t.ClassVar[type[t.Any]]492+class _NumberParamTypeBase(ParamType[ParamTypeValue]):493+ _number_class: t.Callable[[t.Any], ParamTypeValue]494 495 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 lines506 ctx,507 )508 509 510+class NumberRangeInfoDict(ParamTypeInfoDict):511+ min: float | None512+ max: float | None513+ min_open: bool514+ max_open: bool515+ clamp: bool516+517+490-class _NumberRangeBase(_NumberParamTypeBase):518+class _NumberRangeBase(_NumberParamTypeBase[ParamTypeValue]):519 def __init__(520 self,521 min: float | None = None,522 max: float | None = None,6 unmodified lines529 self.min_open = min_open530 self.max_open = max_open531 self.clamp = clamp532 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_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+ }542 543 def convert(544 self, value: t.Any, param: Parameter | None, ctx: Context | None518- ) -> t.Any:545+ ) -> ParamTypeValue:546 import operator547 548 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]557 558 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]561 533- 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]564 565 if lt_min or gt_max:566 self.fail(567 _("{value} is not in the range {range}.").format(4 unmodified lines572 )573 574 return rv575 547- 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.582 583 :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+ ...588 589 def _describe_range(self) -> str:590 """Describe the range for use in help text."""591 if self.min is None:12 unmodified lines604 clamp = " clamped" if self.clamp else ""605 return f"<{type(self).__name__} {self._describe_range()}{clamp}>"606 607 576-class IntParamType(_NumberParamTypeBase):608+class IntParamType(_NumberParamTypeBase[int]):609 name = "integer"610 _number_class = int611 612 def __repr__(self) -> str:613 return "INT"614 615 584-class IntRange(_NumberRangeBase, IntParamType):616+class IntRange(_NumberRangeBase[int], IntParamType):617 """Restrict an :data:`click.INT` value to a range of accepted618 values. See :ref:`ranges`.619 620 If ``min`` or ``max`` are not passed, any value is accepted in that8 unmodified lines629 """630 631 name = "integer range"632 601- 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 bound636 637 return bound + dir638 639 610-class FloatParamType(_NumberParamTypeBase):640+class FloatParamType(_NumberParamTypeBase[float]):641 name = "float"642 _number_class = float643 644 def __repr__(self) -> str:645 return "FLOAT"646 647 618-class FloatRange(_NumberRangeBase, FloatParamType):648+class FloatRange(_NumberRangeBase[float], FloatParamType):649 """Restrict a :data:`click.FLOAT` value to a range of accepted650 values. See :ref:`ranges`.651 652 If ``min`` or ``max`` are not passed, any value is accepted in that34 unmodified lines687 # left up to the user to write a callback to do it if needed.688 raise RuntimeError("Clamping is not supported for open bounds.")689 690 661-class BoolParamType(ParamType):691+class BoolParamType(ParamType[bool]):692 name = "boolean"693 694 bool_states: dict[str, bool] = {695 "1": True,60 unmodified lines756 def __repr__(self) -> str:757 return "BOOL"758 759 730-class UUIDParameterType(ParamType):760+class UUIDParameterType(ParamType[uuid.UUID]):761 name = "uuid"762 763 def convert(764 self, value: t.Any, param: Parameter | None, ctx: Context | None735- ) -> t.Any:736- import uuid737-765+ ) -> uuid.UUID:766 if isinstance(value, uuid.UUID):767 return value768 769 value = value.strip()8 unmodified lines778 def __repr__(self) -> str:779 return "UUID"780 781 754-class File(ParamType):782+class FileInfoDict(ParamTypeInfoDict):783+ mode: str784+ encoding: str | None785+786+787+class 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 lines830 self.errors = errors831 self.lazy = lazy832 self.atomic = atomic833 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_dict834+ def to_info_dict(self) -> FileInfoDict:835+ return {836+ "mode": self.mode,837+ "encoding": self.encoding,838+ **super().to_info_dict(),839+ }840 841 def resolve_lazy_flag(self, value: str | os.PathLike[str]) -> bool:842 if self.lazy is not None:843 return self.lazy66 unmodified lines910 def _is_file_like(value: t.Any) -> te.TypeGuard[t.IO[t.Any]]:911 return hasattr(value, "read") or hasattr(value, "write")912 913 879-class Path(ParamType):914+class PathInfoDict(ParamTypeInfoDict):915+ exists: bool916+ file_okay: bool917+ dir_okay: bool918+ writable: bool919+ readable: bool920+ allow_dash: bool921+922+923+class 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 lines983 self.name = _("directory")984 else:985 self.name = _("path")986 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_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+ }997 998 def coerce_path_result(999 self, value: str | os.PathLike[str]1000 ) -> str | bytes | os.PathLike[str]:98 unmodified lines1099 type = "dir" if self.dir_okay and not self.file_okay else "file"1100 return [CompletionItem(incomplete, type=type)]1101 1102 1060-class Tuple(CompositeParamType):1103+class TupleInfoDict(ParamTypeInfoDict):1104+ types: cabc.Sequence[ParamTypeInfoDict]1105+1106+1107+class 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 used5 unmodified lines1117 1118 :param types: a list of types that should be used for the tuple items.1119 """1120 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]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]1123 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_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+ }1129 1130 @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)}>"1133 1134 @property1087- def arity(self) -> int: # type: ignore1135+ def arity(self) -> int: # type: ignore[override]1136 return len(self.types)1137 1138 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)1143 1144 if len_value != len_type:11 unmodified lines1156 ty(x, param, ctx) for ty, x in zip(self.types, value, strict=False)1157 )1158 1159 1112-def convert_type(ty: t.Any | None, default: t.Any | None = None) -> ParamType:1160+def 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 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