Skip to content
Myr

`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

1 file+148 added−83 removed

modified:src/click/types.py+148 added-83 removed
24 unmodified lines
25 from .core import Context26 from .core import Parameter27 from .shell_completion import CompletionItem2829ParamTypeValue = 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)3233_FloatValueT = t.TypeVar("_FloatValueT", bound=float)34_FloatValueT_co = t.TypeVar("_FloatValueT_co", bound=float, covariant=True)353637class ParamTypeInfoDict(t.TypedDict):38 param_type: str39 name: str404137class ParamType(t.Generic[ParamTypeValue], abc.ABC):42class 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.4546 To implement a custom type, subclass and implement at least the
16 unmodified lines
63 narrowed return type.64 """6566 is_composite: t.ClassVar[bool] = False62 arity: t.ClassVar[int] = 167 arity: int = 1 # read-only6869 #: the descriptive name of this type70 name: str71
30 unmodified lines
102 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 lines
119 """120121 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).126127 This must accept string values from the command line, as well as
13 unmodified lines
141 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)146147 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 lines
180 """181 return []182183179class CompositeParamType(ParamType[ParamTypeValue]):180 is_composite = True184class CompositeParamType(ParamType[_ValueT_co]):185 is_composite: t.ClassVar[bool] = True186187 @property188 @abc.abstractmethod189 def arity(self) -> int: ... # type: ignore[override]190191187class FuncParamTypeInfoDict(ParamTypeInfoDict):188 func: t.Callable[[t.Any], t.Any]192if t.TYPE_CHECKING:193 # on Python 3.10 this will raise a TypeError194195 class FuncParamTypeInfoDict(196 ParamTypeInfoDict,197 t.Generic[_ValueT_contra, _ValueT_co],198 ):199 func: t.Callable[[_ValueT_contra], _ValueT_co]200else:201191class 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]204205206class FuncParamType(ParamType[_ValueT_co], t.Generic[_ValueT_contra, _ValueT_co]):207 name: str208 func: t.Callable[[_ValueT_contra], _ValueT_co]209210 def __init__(self, func: t.Callable[[_ValueT_contra], _ValueT_co]) -> None:211 self.name = func.__name__212 self.func = func213196 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()}216217 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 line
225 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")230231 self.fail(message, param, ctx)232233234class UnprocessedParamType(ParamType[t.Any]):235 name = "text"236237 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 value241242 def __repr__(self) -> str:243 return "UNPROCESSED"
7 unmodified lines
251 ) -> 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)266267 def __repr__(self) -> str:268 return "STRING"269270254class ChoiceInfoDict(ParamTypeInfoDict):255 choices: cabc.Sequence[t.Any]256 case_sensitive: bool271if t.TYPE_CHECKING:272 # on Python 3.10 this will raise a TypeError273274 class ChoiceInfoDict(ParamTypeInfoDict, t.Generic[_ValueT_co]):275 choices: tuple[_ValueT_co, ...]276 case_sensitive: bool277else:278259class Choice(ParamType[ParamTypeValue], t.Generic[ParamTypeValue]):279 class ChoiceInfoDict(ParamTypeInfoDict):280 choices: tuple[t.Any, ...]281 case_sensitive: bool282283284class 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.287288 You may pass any iterable value which will be converted to a tuple
19 unmodified lines
308 .. versionadded:: 8.2.0309 Choice normalization can be overridden via :meth:`normalize_choice`.310 """311287 name = "choice"312 name: str = "choice"313314 choices: tuple[_ValueT_co, ...]315 case_sensitive: bool316317 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_sensitive322295 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 }329330 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 lines
344 )345 for choice in self.choices346 }347320 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 lines
365366 return normed_value367368 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 lines
394 )395396 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 lines
483 """484485 name = "datetime"486487 formats: cabc.Sequence[str]488489 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 ]495496 def to_info_dict(self) -> DateTimeInfoDict:497 return {"formats": self.formats, **super().to_info_dict()}498469 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)}]"501502 def _try_to_convert_date(self, value: t.Any, format: str) -> datetime | None:503 try:
27 unmodified lines
531 def __repr__(self) -> str:532 return "DateTime"533534505class _NumberParamTypeBase(ParamType[ParamTypeValue]):506 _number_class: t.Callable[[t.Any], ParamTypeValue]535class _NumberParamTypeBase(536 ParamType[_ValueT_co], t.Generic[_ValueT_contra, _ValueT_co]537):538 _number_class: t.Callable[[_ValueT_contra], _ValueT_co]539540 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 lines
551 ctx,552 )553554555if t.TYPE_CHECKING:556 # on Python 3.10 this will raise a TypeError557558 class NumberRangeInfoDict(ParamTypeInfoDict, t.Generic[_FloatValueT_co]):559 min: _FloatValueT_co | None560 max: _FloatValueT_co | None561 min_open: bool562 max_open: bool563 clamp: bool564else:565523class 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: bool572573574class _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: bool583530531class _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 lines
594 self.min_open = min_open595 self.max_open = max_open596 self.clamp = clamp597546 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 lines
605 **super().to_info_dict(),606 }607608 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 operator612613 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)622623 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)626627 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)629630 if lt_min or gt_max:631 self.fail(632 _("{value} is not in the range {range}.").format(
6 unmodified lines
639 return rv640641 @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.652653 :param bound: The boundary value.
20 unmodified lines
674 clamp = " clamped" if self.clamp else ""675 return f"<{type(self).__name__} {self._describe_range()}{clamp}>"676677621class IntParamType(_NumberParamTypeBase[int]):678class IntParamType(_NumberParamTypeBase[t.SupportsInt | t.SupportsIndex, int]):679 name = "integer"680 _number_class = int681682 def __repr__(self) -> str:683 return "INT"684685629class IntRange(_NumberRangeBase[int], IntParamType):686class IntRange(_NumberRangeBase[int, int], IntParamType):687 """Restrict an :data:`click.INT` value to a range of accepted688 values. See :ref:`ranges`.689690 If ``min`` or ``max`` are not passed, any value is accepted in that
15 unmodified lines
706707 return bound + dir708709653class FloatParamType(_NumberParamTypeBase[float]):710class FloatParamType(_NumberParamTypeBase[t.SupportsFloat | t.SupportsIndex, float]):711 name = "float"712 _number_class = float713714 def __repr__(self) -> str:715 return "FLOAT"716717661class FloatRange(_NumberRangeBase[float], FloatParamType):718class FloatRange(_NumberRangeBase[float, float], FloatParamType):719 """Restrict a :data:`click.FLOAT` value to a range of accepted720 values. See :ref:`ranges`.721722 If ``min`` or ``max`` are not passed, any value is accepted in that
107 unmodified lines
830class UUIDParameterType(ParamType[uuid.UUID]):831 name = "uuid"832833 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 lines
886887 name = "filename"888 envvar_list_splitter: t.ClassVar[str] = os.path.pathsep889890 mode: str891 encoding: str | None892 errors: str | None893 lazy: bool | None894 atomic: bool895896 def __init__(897 self,898 mode: str = "r",899 encoding: str | None = None,
31 unmodified lines
931 ) -> t.IO[t.Any]:932 if _is_file_like(value):933 return value934872 value = t.cast("str | os.PathLike[str]", value)873935 try:936 lazy = self.resolve_lazy_flag(value)937938 if lazy:
45 unmodified lines
984985 return [CompletionItem(incomplete, type="file")]986987927def _is_file_like(value: t.Any) -> te.TypeGuard[t.IO[t.Any]]:988def _is_file_like(value: t.Any) -> te.TypeIs[t.IO[t.Any]]:989 return hasattr(value, "read") or hasattr(value, "write")990991992class PathInfoDict(ParamTypeInfoDict):
39 unmodified lines
1032 """10331034 envvar_list_splitter: t.ClassVar[str] = os.path.pathsep10351036 exists: bool1037 file_okay: bool1038 dir_okay: bool1039 readable: bool1040 writable: bool1041 executable: bool1042 resolve_path: bool1043 allow_dash: bool1044 name: str10451046 def __init__(1047 self,1048 exists: bool = False,1049 file_okay: bool = True,
1 unmodified line
1051 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_type10671068 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 lines
128112821283@t.overload1284def convert_type(ty: None, default: None = None) -> StringParamType: ...121412151285@t.overload1286def 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]: ...122012211289@t.overload1290def convert_type(1291 ty: t.Any | None, default: t.Any | None = None1292) -> ParamType[t.Any]: ...122612271293def 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 Python
47 unmodified lines
1344#: there are situations where an unprocessed type is useful which is why1345#: it is provided.1346#:1347#: .. versionadded:: 4.01283UNPROCESSED = UnprocessedParamType()1348UNPROCESSED: t.Final[UnprocessedParamType] = UnprocessedParamType()13491350#: A unicode string parameter type which is the implicit default. This1351#: can also be selected by using ``str`` as type.1287STRING = StringParamType()1352STRING: t.Final[StringParamType] = StringParamType()13531354#: An integer parameter. This can also be selected by using ``int`` as1355#: type.1291INT = IntParamType()1356INT: t.Final[IntParamType] = IntParamType()13571358#: A floating point value parameter. This can also be selected by using1359#: ``float`` as type.1295FLOAT = FloatParamType()1360FLOAT: t.Final[FloatParamType] = FloatParamType()13611362#: A boolean parameter. This is the default for boolean flags. This can1363#: also be selected by using ``bool`` as a type.1299BOOL = BoolParamType()1364BOOL: t.Final[BoolParamType] = BoolParamType()13651366#: A UUID parameter.1302UUID = UUIDParameterType()1367UUID: t.Final[UUIDParameterType] = UUIDParameterType()136813691370class OptionHelpExtra(t.TypedDict, total=False):1371 envvars: tuple[str, ...]
3 unmodified lines