`types`: fix variance issues and improve type coverage (#3450)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Rowlando13 · committed by GitHub · parents e34e526, 9a2d169 · Browse files · 1 file·+148 added−83 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+148 added−83 removed
- other:+148 added−83 removed
Provenance
- Commit
65feb61- Tree
88b5fa5- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
e34e526- Parent 2
9a2d169
1 file changed+148 added−83 removed
modified:src/click/types.py+148 added-83 removed
24 unmodified lines25 from .core import Context26 from .core import Parameter27 from .shell_completion import CompletionItem28 29-ParamTypeValue = t.TypeVar("ParamTypeValue")29+_ValueT = t.TypeVar("_ValueT")30+_ValueT_contra = t.TypeVar("_ValueT_contra", contravariant=True)31+_ValueT_co = t.TypeVar("_ValueT_co", covariant=True)32 33+_FloatValueT = t.TypeVar("_FloatValueT", bound=float)34+_FloatValueT_co = t.TypeVar("_FloatValueT_co", bound=float, covariant=True)35 36+37 class ParamTypeInfoDict(t.TypedDict):38 param_type: str39 name: str40 41 37-class ParamType(t.Generic[ParamTypeValue], abc.ABC):42+class ParamType(t.Generic[_ValueT_co], abc.ABC):43 """Represents the type of a parameter. Validates and converts values44 from the command line or Python into the correct type.45 46 To implement a custom type, subclass and implement at least the16 unmodified lines63 narrowed return type.64 """65 66 is_composite: t.ClassVar[bool] = False62- arity: t.ClassVar[int] = 167+ arity: int = 1 # read-only68 69 #: the descriptive name of this type70 name: str71 30 unmodified lines102 self,103 value: t.Any,104 param: Parameter | None = None,105 ctx: Context | None = None,101- ) -> ParamTypeValue | None:106+ ) -> _ValueT_co | None:107 if value is not None:108 return self.convert(value, param, ctx)109 return None110 8 unmodified lines119 """120 121 def convert(122 self, value: t.Any, param: Parameter | None, ctx: Context | None118- ) -> ParamTypeValue:123+ ) -> _ValueT_co:124 """Convert the value to the correct type. This is not called if125 the value is ``None`` (the missing value).126 127 This must accept string values from the command line, as well as13 unmodified lines141 be ``None``.142 """143 # The default returns the value as-is so subclasses that only customize144 # metadata are not forced to redeclare ``convert``.140- return t.cast("ParamTypeValue", value)145+ return t.cast("_ValueT_co", value)146 147 def split_envvar_value(self, rv: str) -> cabc.Sequence[str]:148 """Given a value from an environment variable this splits it up149 into small chunks depending on the defined envvar list splitter.30 unmodified lines180 """181 return []182 183 179-class CompositeParamType(ParamType[ParamTypeValue]):180- is_composite = True184+class CompositeParamType(ParamType[_ValueT_co]):185+ is_composite: t.ClassVar[bool] = True186 187 @property188 @abc.abstractmethod189 def arity(self) -> int: ... # type: ignore[override]190 191 187-class FuncParamTypeInfoDict(ParamTypeInfoDict):188- func: t.Callable[[t.Any], t.Any]192+if t.TYPE_CHECKING:193+ # on Python 3.10 this will raise a TypeError194 195+ class FuncParamTypeInfoDict(196+ ParamTypeInfoDict,197+ t.Generic[_ValueT_contra, _ValueT_co],198+ ):199+ func: t.Callable[[_ValueT_contra], _ValueT_co]200+else:201 191-class FuncParamType(ParamType[ParamTypeValue]):192- def __init__(self, func: t.Callable[[t.Any], ParamTypeValue]) -> None:193- self.name: str = func.__name__202+ class FuncParamTypeInfoDict(ParamTypeInfoDict):203+ func: t.Callable[[t.Any], t.Any]204+205+206+class FuncParamType(ParamType[_ValueT_co], t.Generic[_ValueT_contra, _ValueT_co]):207+ name: str208+ func: t.Callable[[_ValueT_contra], _ValueT_co]209+210+ def __init__(self, func: t.Callable[[_ValueT_contra], _ValueT_co]) -> None:211+ self.name = func.__name__212 self.func = func213 196- def to_info_dict(self) -> FuncParamTypeInfoDict:214+ def to_info_dict(self) -> FuncParamTypeInfoDict[_ValueT_contra, _ValueT_co]:215 return {"func": self.func, **super().to_info_dict()}216 217 def convert(200- self, value: t.Any, param: Parameter | None, ctx: Context | None201- ) -> ParamTypeValue:218+ self, value: _ValueT_contra, param: Parameter | None, ctx: Context | None219+ ) -> _ValueT_co:220 try:221 return self.func(value)222 except ValueError as exc:223 message = str(exc)1 unmodified line225 if not message:226 try:227 message = str(value)228 except UnicodeError:211- message = value.decode("utf-8", "replace")229+ message = t.cast("bytes", value).decode("utf-8", "replace")230 231 self.fail(message, param, ctx)232 233 234 class UnprocessedParamType(ParamType[t.Any]):235 name = "text"236 237 def convert(220- self, value: t.Any, param: Parameter | None, ctx: Context | None221- ) -> t.Any:238+ self, value: _ValueT, param: Parameter | None, ctx: Context | None239+ ) -> _ValueT:240 return value241 242 def __repr__(self) -> str:243 return "UNPROCESSED"7 unmodified lines251 ) -> str:252 if isinstance(value, bytes):253 enc = _get_argv_encoding()254 try:237- value = value.decode(enc)255+ return value.decode(enc)256 except UnicodeError:257 fs_enc = sys.getfilesystemencoding()258 if fs_enc != enc:259 try:242- value = value.decode(fs_enc)260+ return value.decode(fs_enc)261 except UnicodeError:244- value = value.decode("utf-8", "replace")262+ return value.decode("utf-8", "replace")263 else:246- value = value.decode("utf-8", "replace")247- return value # type: ignore[no-any-return]264+ return value.decode("utf-8", "replace")265 return str(value)266 267 def __repr__(self) -> str:268 return "STRING"269 270 254-class ChoiceInfoDict(ParamTypeInfoDict):255- choices: cabc.Sequence[t.Any]256- case_sensitive: bool271+if t.TYPE_CHECKING:272+ # on Python 3.10 this will raise a TypeError273 274+ class ChoiceInfoDict(ParamTypeInfoDict, t.Generic[_ValueT_co]):275+ choices: tuple[_ValueT_co, ...]276+ case_sensitive: bool277+else:278 259-class Choice(ParamType[ParamTypeValue], t.Generic[ParamTypeValue]):279+ class ChoiceInfoDict(ParamTypeInfoDict):280+ choices: tuple[t.Any, ...]281+ case_sensitive: bool282+283+284+class Choice(ParamType[_ValueT_co], t.Generic[_ValueT_co]):285 """The choice type allows a value to be checked against a fixed set286 of supported values.287 288 You may pass any iterable value which will be converted to a tuple19 unmodified lines308 .. versionadded:: 8.2.0309 Choice normalization can be overridden via :meth:`normalize_choice`.310 """311 287- name = "choice"312+ name: str = "choice"313 314+ choices: tuple[_ValueT_co, ...]315+ case_sensitive: bool316+317 def __init__(290- self, choices: cabc.Iterable[ParamTypeValue], case_sensitive: bool = True318+ self, choices: cabc.Iterable[_ValueT_co], case_sensitive: bool = True319 ) -> None:292- self.choices: cabc.Sequence[ParamTypeValue] = tuple(choices)320+ self.choices = tuple(choices)321 self.case_sensitive = case_sensitive322 295- def to_info_dict(self) -> ChoiceInfoDict:323+ def to_info_dict(self) -> ChoiceInfoDict[_ValueT_co]:324 return {325 "choices": self.choices,326 "case_sensitive": self.case_sensitive,327 **super().to_info_dict(),328 }329 330 def _normalized_mapping(331 self, ctx: Context | None = None304- ) -> cabc.Mapping[ParamTypeValue, str]:332+ ) -> cabc.Mapping[_ValueT_co, str]:333 """334 Returns mapping where keys are the original choices and the values are335 the normalized values that are accepted via the command line.336 7 unmodified lines344 )345 for choice in self.choices346 }347 320- def normalize_choice(self, choice: ParamTypeValue, ctx: Context | None) -> str:348+ def normalize_choice(self, choice: object, ctx: Context | None) -> str:349 """350 Normalize a choice value, used to map a passed string to a choice.351 Each choice must have a unique normalized value.352 12 unmodified lines365 366 return normed_value367 368 def get_metavar(self, param: Parameter, ctx: Context) -> str | None:341- if param.param_type_name == "option" and not param.show_choices: # type: ignore369+ if param.param_type_name == "option" and not param.show_choices: # type: ignore[attr-defined]370 choice_metavars = [371 convert_type(type(choice)).name.upper() for choice in self.choices372 ]373 choices_str = "|".join([*dict.fromkeys(choice_metavars)])20 unmodified lines394 )395 396 def convert(397 self, value: t.Any, param: Parameter | None, ctx: Context | None370- ) -> ParamTypeValue:398+ ) -> _ValueT_co:399 """400 For a given value from the parser, normalize it and find its401 matching normalized value in the list of choices. Then return the402 matched "original" choice.80 unmodified lines483 """484 485 name = "datetime"486 487+ formats: cabc.Sequence[str]488+489 def __init__(self, formats: cabc.Sequence[str] | None = None):460- self.formats: cabc.Sequence[str] = formats or [490+ self.formats = formats or [491 "%Y-%m-%d",492 "%Y-%m-%dT%H:%M:%S",493 "%Y-%m-%d %H:%M:%S",494 ]495 496 def to_info_dict(self) -> DateTimeInfoDict:497 return {"formats": self.formats, **super().to_info_dict()}498 469- def get_metavar(self, param: Parameter, ctx: Context) -> str | None:499+ def get_metavar(self, param: Parameter, ctx: Context) -> str:500 return f"[{'|'.join(self.formats)}]"501 502 def _try_to_convert_date(self, value: t.Any, format: str) -> datetime | None:503 try:27 unmodified lines531 def __repr__(self) -> str:532 return "DateTime"533 534 505-class _NumberParamTypeBase(ParamType[ParamTypeValue]):506- _number_class: t.Callable[[t.Any], ParamTypeValue]535+class _NumberParamTypeBase(536+ ParamType[_ValueT_co], t.Generic[_ValueT_contra, _ValueT_co]537+):538+ _number_class: t.Callable[[_ValueT_contra], _ValueT_co]539 540 def convert(509- self, value: t.Any, param: Parameter | None, ctx: Context | None510- ) -> ParamTypeValue:541+ self, value: _ValueT_contra, param: Parameter | None, ctx: Context | None542+ ) -> _ValueT_co:543 try:544 return self._number_class(value)545 except ValueError:546 self.fail(4 unmodified lines551 ctx,552 )553 554 555+if t.TYPE_CHECKING:556+ # on Python 3.10 this will raise a TypeError557+558+ class NumberRangeInfoDict(ParamTypeInfoDict, t.Generic[_FloatValueT_co]):559+ min: _FloatValueT_co | None560+ max: _FloatValueT_co | None561+ min_open: bool562+ max_open: bool563+ clamp: bool564+else:565+523-class NumberRangeInfoDict(ParamTypeInfoDict):524- min: float | None525- max: float | None566+ class NumberRangeInfoDict(ParamTypeInfoDict):567+ min: t.Any | None568+ max: t.Any | None569+ min_open: bool570+ max_open: bool571+ clamp: bool572+573+574+class _NumberRangeBase(575+ _NumberParamTypeBase[_ValueT_contra, _FloatValueT_co],576+ t.Generic[_ValueT_contra, _FloatValueT_co],577+):578+ min: _FloatValueT_co | None579+ max: _FloatValueT_co | None580 min_open: bool581 max_open: bool582 clamp: bool583 530-531-class _NumberRangeBase(_NumberParamTypeBase[ParamTypeValue]):584 def __init__(585 self,534- min: float | None = None,535- max: float | None = None,586+ min: _FloatValueT_co | None = None,587+ max: _FloatValueT_co | None = None,588 min_open: bool = False,589 max_open: bool = False,590 clamp: bool = False,591 ) -> None:2 unmodified lines594 self.min_open = min_open595 self.max_open = max_open596 self.clamp = clamp597 546- def to_info_dict(self) -> NumberRangeInfoDict:598+ def to_info_dict(self) -> NumberRangeInfoDict[_FloatValueT_co]:599 return {600 "min": self.min,601 "max": self.max,602 "min_open": self.min_open,2 unmodified lines605 **super().to_info_dict(),606 }607 608 def convert(557- self, value: t.Any, param: Parameter | None, ctx: Context | None558- ) -> ParamTypeValue:609+ self, value: _ValueT_contra, param: Parameter | None, ctx: Context | None610+ ) -> _FloatValueT_co:611 import operator612 613 rv = super().convert(value, param, ctx)614 min = self.min615 max = self.max616 lt_min: bool = min is not None and (617 operator.le if self.min_open else operator.lt566- )(rv, min) # type: ignore[arg-type]618+ )(rv, min)619 gt_max: bool = max is not None and (620 operator.ge if self.max_open else operator.gt569- )(rv, max) # type: ignore[arg-type]621+ )(rv, max)622 623 if self.clamp:624 if min is not None and lt_min:573- return self._clamp(min, 1, self.min_open) # type: ignore[arg-type]625+ return self._clamp(min, 1, self.min_open)626 627 if max is not None and gt_max:576- return self._clamp(max, -1, self.max_open) # type: ignore[arg-type]628+ return self._clamp(max, -1, self.max_open)629 630 if lt_min or gt_max:631 self.fail(632 _("{value} is not in the range {range}.").format(6 unmodified lines639 return rv640 641 @abc.abstractmethod642 def _clamp(591- self, bound: ParamTypeValue, dir: t.Literal[1, -1], open: bool592- ) -> ParamTypeValue:643+ # Covariant type variables cannot be used in input positions, so we use a644+ # separate method-scoped type variable instead.645+ self: _NumberRangeBase[t.Any, _FloatValueT],646+ bound: _FloatValueT,647+ dir: t.Literal[1, -1],648+ open: bool,649+ ) -> _FloatValueT:650 """Find the valid value to clamp to bound in the given651 direction.652 653 :param bound: The boundary value.20 unmodified lines674 clamp = " clamped" if self.clamp else ""675 return f"<{type(self).__name__} {self._describe_range()}{clamp}>"676 677 621-class IntParamType(_NumberParamTypeBase[int]):678+class IntParamType(_NumberParamTypeBase[t.SupportsInt | t.SupportsIndex, int]):679 name = "integer"680 _number_class = int681 682 def __repr__(self) -> str:683 return "INT"684 685 629-class IntRange(_NumberRangeBase[int], IntParamType):686+class IntRange(_NumberRangeBase[int, int], IntParamType):687 """Restrict an :data:`click.INT` value to a range of accepted688 values. See :ref:`ranges`.689 690 If ``min`` or ``max`` are not passed, any value is accepted in that15 unmodified lines706 707 return bound + dir708 709 653-class FloatParamType(_NumberParamTypeBase[float]):710+class FloatParamType(_NumberParamTypeBase[t.SupportsFloat | t.SupportsIndex, float]):711 name = "float"712 _number_class = float713 714 def __repr__(self) -> str:715 return "FLOAT"716 717 661-class FloatRange(_NumberRangeBase[float], FloatParamType):718+class FloatRange(_NumberRangeBase[float, float], FloatParamType):719 """Restrict a :data:`click.FLOAT` value to a range of accepted720 values. See :ref:`ranges`.721 722 If ``min`` or ``max`` are not passed, any value is accepted in that107 unmodified lines830 class UUIDParameterType(ParamType[uuid.UUID]):831 name = "uuid"832 833 def convert(777- self, value: t.Any, param: Parameter | None, ctx: Context | None834+ self, value: uuid.UUID | str, param: Parameter | None, ctx: Context | None835 ) -> uuid.UUID:836 if isinstance(value, uuid.UUID):837 return value838 47 unmodified lines886 887 name = "filename"888 envvar_list_splitter: t.ClassVar[str] = os.path.pathsep889 890+ mode: str891+ encoding: str | None892+ errors: str | None893+ lazy: bool | None894+ atomic: bool895+896 def __init__(897 self,898 mode: str = "r",899 encoding: str | None = None,31 unmodified lines931 ) -> t.IO[t.Any]:932 if _is_file_like(value):933 return value934 872- value = t.cast("str | os.PathLike[str]", value)873-935 try:936 lazy = self.resolve_lazy_flag(value)937 938 if lazy:45 unmodified lines984 985 return [CompletionItem(incomplete, type="file")]986 987 927-def _is_file_like(value: t.Any) -> te.TypeGuard[t.IO[t.Any]]:988+def _is_file_like(value: t.Any) -> te.TypeIs[t.IO[t.Any]]:989 return hasattr(value, "read") or hasattr(value, "write")990 991 992 class PathInfoDict(ParamTypeInfoDict):39 unmodified lines1032 """1033 1034 envvar_list_splitter: t.ClassVar[str] = os.path.pathsep1035 1036+ exists: bool1037+ file_okay: bool1038+ dir_okay: bool1039+ readable: bool1040+ writable: bool1041+ executable: bool1042+ resolve_path: bool1043+ allow_dash: bool1044+ name: str1045+1046 def __init__(1047 self,1048 exists: bool = False,1049 file_okay: bool = True,1 unmodified line1051 writable: bool = False,1052 readable: bool = True,1053 resolve_path: bool = False,1054 allow_dash: bool = False,984- path_type: type[t.Any] | None = None,1055+ path_type: type | None = None,1056 executable: bool = False,986- ):1057+ ) -> None:1058 self.exists = exists1059 self.file_okay = file_okay1060 self.dir_okay = dir_okay1061 self.readable = readable1062 self.writable = writable1063 self.executable = executable1064 self.resolve_path = resolve_path1065 self.allow_dash = allow_dash995- self.type = path_type1066+ self.type: type | None = path_type1067 1068 if self.file_okay and not self.dir_okay:998- self.name: str = _("file")1069+ self.name = _("file")1070 elif self.dir_okay and not self.file_okay:1071 self.name = _("directory")1072 else:1073 self.name = _("path")207 unmodified lines1281 1282 1283 @t.overload1284 def convert_type(ty: None, default: None = None) -> StringParamType: ...1214-1215-1285 @t.overload1286 def convert_type(1218- ty: type[t.Any] | ParamType[t.Any], default: t.Any | None = None1287+ ty: type | ParamType[t.Any], default: t.Any | None = None1288 ) -> ParamType[t.Any]: ...1220-1221-1289 @t.overload1290 def convert_type(1291 ty: t.Any | None, default: t.Any | None = None1292 ) -> ParamType[t.Any]: ...1226-1227-1293 def convert_type(1294 ty: t.Any | None = None, default: t.Any | None = None1295 ) -> ParamType[t.Any]:1296 """Find the most appropriate :class:`ParamType` for the given Python47 unmodified lines1344 #: there are situations where an unprocessed type is useful which is why1345 #: it is provided.1346 #:1347 #: .. versionadded:: 4.01283-UNPROCESSED = UnprocessedParamType()1348+UNPROCESSED: t.Final[UnprocessedParamType] = UnprocessedParamType()1349 1350 #: A unicode string parameter type which is the implicit default. This1351 #: can also be selected by using ``str`` as type.1287-STRING = StringParamType()1352+STRING: t.Final[StringParamType] = StringParamType()1353 1354 #: An integer parameter. This can also be selected by using ``int`` as1355 #: type.1291-INT = IntParamType()1356+INT: t.Final[IntParamType] = IntParamType()1357 1358 #: A floating point value parameter. This can also be selected by using1359 #: ``float`` as type.1295-FLOAT = FloatParamType()1360+FLOAT: t.Final[FloatParamType] = FloatParamType()1361 1362 #: A boolean parameter. This is the default for boolean flags. This can1363 #: also be selected by using ``bool`` as a type.1299-BOOL = BoolParamType()1364+BOOL: t.Final[BoolParamType] = BoolParamType()1365 1366 #: A UUID parameter.1302-UUID = UUIDParameterType()1367+UUID: t.Final[UUIDParameterType] = UUIDParameterType()1368 1369 1370 class OptionHelpExtra(t.TypedDict, total=False):1371 envvars: tuple[str, ...]3 unmodified lines