Skip to content
Myr

`types`: fix variance issues and improve type coverage

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

authored by jorenham · committed by jorenham · parent 648d7c4 · Browse files · 1 file+117 added−81 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+117 added−81 removed

  • other:+117 added−81 removed

1 file+117 added−81 removed

modified:src/click/types.py+117 added-81 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]192class FuncParamTypeInfoDict(ParamTypeInfoDict, t.Generic[_ValueT_contra, _ValueT_co]):193 func: t.Callable[[_ValueT_contra], _ValueT_co]194195191class FuncParamType(ParamType[ParamTypeValue]):192 def __init__(self, func: t.Callable[[t.Any], ParamTypeValue]) -> None:193 self.name: str = func.__name__196class FuncParamType(ParamType[_ValueT_co], t.Generic[_ValueT_contra, _ValueT_co]):197 name: str198 func: t.Callable[[_ValueT_contra], _ValueT_co]199200 def __init__(self, func: t.Callable[[_ValueT_contra], _ValueT_co]) -> None:201 self.name = func.__name__202 self.func = func203196 def to_info_dict(self) -> FuncParamTypeInfoDict:204 def to_info_dict(self) -> FuncParamTypeInfoDict[_ValueT_contra, _ValueT_co]:205 return {"func": self.func, **super().to_info_dict()}206207 def convert(200 self, value: t.Any, param: Parameter | None, ctx: Context | None201 ) -> ParamTypeValue:208 self, value: _ValueT_contra, param: Parameter | None, ctx: Context | None209 ) -> _ValueT_co:210 try:211 return self.func(value)212 except ValueError as exc:213 message = str(exc)
1 unmodified line
215 if not message:216 try:217 message = str(value)218 except UnicodeError:211 message = value.decode("utf-8", "replace")219 message = t.cast("bytes", value).decode("utf-8", "replace")220221 self.fail(message, param, ctx)222223224class UnprocessedParamType(ParamType[t.Any]):225 name = "text"226227 def convert(220 self, value: t.Any, param: Parameter | None, ctx: Context | None221 ) -> t.Any:228 self, value: _ValueT, param: Parameter | None, ctx: Context | None229 ) -> _ValueT:230 return value231232 def __repr__(self) -> str:233 return "UNPROCESSED"
7 unmodified lines
241 ) -> str:242 if isinstance(value, bytes):243 enc = _get_argv_encoding()244 try:237 value = value.decode(enc)245 return value.decode(enc)246 except UnicodeError:247 fs_enc = sys.getfilesystemencoding()248 if fs_enc != enc:249 try:242 value = value.decode(fs_enc)250 return value.decode(fs_enc)251 except UnicodeError:244 value = value.decode("utf-8", "replace")252 return value.decode("utf-8", "replace")253 else:246 value = value.decode("utf-8", "replace")247 return value # type: ignore[no-any-return]254 return value.decode("utf-8", "replace")255 return str(value)256257 def __repr__(self) -> str:258 return "STRING"259260254class ChoiceInfoDict(ParamTypeInfoDict):255 choices: cabc.Sequence[t.Any]261class ChoiceInfoDict(ParamTypeInfoDict, t.Generic[_ValueT_co]):262 choices: tuple[_ValueT_co, ...]263 case_sensitive: bool264265259class Choice(ParamType[ParamTypeValue], t.Generic[ParamTypeValue]):266class Choice(ParamType[_ValueT_co], t.Generic[_ValueT_co]):267 """The choice type allows a value to be checked against a fixed set268 of supported values.269270 You may pass any iterable value which will be converted to a tuple
19 unmodified lines
290 .. versionadded:: 8.2.0291 Choice normalization can be overridden via :meth:`normalize_choice`.292 """293287 name = "choice"294 name: str = "choice"295296 choices: tuple[_ValueT_co, ...]297 case_sensitive: bool298299 def __init__(290 self, choices: cabc.Iterable[ParamTypeValue], case_sensitive: bool = True300 self, choices: cabc.Iterable[_ValueT_co], case_sensitive: bool = True301 ) -> None:292 self.choices: cabc.Sequence[ParamTypeValue] = tuple(choices)302 self.choices = tuple(choices)303 self.case_sensitive = case_sensitive304295 def to_info_dict(self) -> ChoiceInfoDict:305 def to_info_dict(self) -> ChoiceInfoDict[_ValueT_co]:306 return {307 "choices": self.choices,308 "case_sensitive": self.case_sensitive,309 **super().to_info_dict(),310 }311312 def _normalized_mapping(313 self, ctx: Context | None = None304 ) -> cabc.Mapping[ParamTypeValue, str]:314 ) -> cabc.Mapping[_ValueT_co, str]:315 """316 Returns mapping where keys are the original choices and the values are317 the normalized values that are accepted via the command line.318
7 unmodified lines
326 )327 for choice in self.choices328 }329320 def normalize_choice(self, choice: ParamTypeValue, ctx: Context | None) -> str:330 def normalize_choice(self, choice: object, ctx: Context | None) -> str:331 """332 Normalize a choice value, used to map a passed string to a choice.333 Each choice must have a unique normalized value.334
12 unmodified lines
347348 return normed_value349350 def get_metavar(self, param: Parameter, ctx: Context) -> str | None:341 if param.param_type_name == "option" and not param.show_choices: # type: ignore351 if param.param_type_name == "option" and not param.show_choices: # type: ignore[attr-defined]352 choice_metavars = [353 convert_type(type(choice)).name.upper() for choice in self.choices354 ]355 choices_str = "|".join([*dict.fromkeys(choice_metavars)])
20 unmodified lines
376 )377378 def convert(379 self, value: t.Any, param: Parameter | None, ctx: Context | None370 ) -> ParamTypeValue:380 ) -> _ValueT_co:381 """382 For a given value from the parser, normalize it and find its383 matching normalized value in the list of choices. Then return the384 matched "original" choice.
80 unmodified lines
465 """466467 name = "datetime"468469 formats: cabc.Sequence[str]470471 def __init__(self, formats: cabc.Sequence[str] | None = None):460 self.formats: cabc.Sequence[str] = formats or [472 self.formats = formats or [473 "%Y-%m-%d",474 "%Y-%m-%dT%H:%M:%S",475 "%Y-%m-%d %H:%M:%S",476 ]477478 def to_info_dict(self) -> DateTimeInfoDict:479 return {"formats": self.formats, **super().to_info_dict()}480469 def get_metavar(self, param: Parameter, ctx: Context) -> str | None:481 def get_metavar(self, param: Parameter, ctx: Context) -> str:482 return f"[{'|'.join(self.formats)}]"483484 def _try_to_convert_date(self, value: t.Any, format: str) -> datetime | None:485 try:
27 unmodified lines
513 def __repr__(self) -> str:514 return "DateTime"515516505class _NumberParamTypeBase(ParamType[ParamTypeValue]):506 _number_class: t.Callable[[t.Any], ParamTypeValue]517class _NumberParamTypeBase(518 ParamType[_ValueT_co], t.Generic[_ValueT_contra, _ValueT_co]519):520 _number_class: t.Callable[[_ValueT_contra], _ValueT_co]521522 def convert(509 self, value: t.Any, param: Parameter | None, ctx: Context | None510 ) -> ParamTypeValue:523 self, value: _ValueT_contra, param: Parameter | None, ctx: Context | None524 ) -> _ValueT_co:525 try:526 return self._number_class(value)527 except ValueError:528 self.fail(
4 unmodified lines
533 ctx,534 )535536523class NumberRangeInfoDict(ParamTypeInfoDict):524 min: float | None525 max: float | None537class NumberRangeInfoDict(ParamTypeInfoDict, t.Generic[_FloatValueT_co]):538 min: _FloatValueT_co | None539 max: _FloatValueT_co | None540 min_open: bool541 max_open: bool542 clamp: bool543544531class _NumberRangeBase(_NumberParamTypeBase[ParamTypeValue]):545class _NumberRangeBase(546 _NumberParamTypeBase[_ValueT_contra, _FloatValueT_co],547 t.Generic[_ValueT_contra, _FloatValueT_co],548):549 min: _FloatValueT_co | None550 max: _FloatValueT_co | None551 min_open: bool552 max_open: bool553 clamp: bool554555 def __init__(556 self,534 min: float | None = None,535 max: float | None = None,557 min: _FloatValueT_co | None = None,558 max: _FloatValueT_co | None = None,559 min_open: bool = False,560 max_open: bool = False,561 clamp: bool = False,562 ) -> None:
2 unmodified lines
565 self.min_open = min_open566 self.max_open = max_open567 self.clamp = clamp568546 def to_info_dict(self) -> NumberRangeInfoDict:569 def to_info_dict(self) -> NumberRangeInfoDict[_FloatValueT_co]:570 return {571 "min": self.min,572 "max": self.max,573 "min_open": self.min_open,
2 unmodified lines
576 **super().to_info_dict(),577 }578579 def convert(557 self, value: t.Any, param: Parameter | None, ctx: Context | None558 ) -> ParamTypeValue:580 self, value: _ValueT_contra, param: Parameter | None, ctx: Context | None581 ) -> _FloatValueT_co:582 import operator583584 rv = super().convert(value, param, ctx)585 min = self.min586 max = self.max587 lt_min: bool = min is not None and (588 operator.le if self.min_open else operator.lt566 )(rv, min) # type: ignore[arg-type]589 )(rv, min)590 gt_max: bool = max is not None and (591 operator.ge if self.max_open else operator.gt569 )(rv, max) # type: ignore[arg-type]592 )(rv, max)593594 if self.clamp:595 if min is not None and lt_min:573 return self._clamp(min, 1, self.min_open) # type: ignore[arg-type]596 return self._clamp(min, 1, self.min_open)597598 if max is not None and gt_max:576 return self._clamp(max, -1, self.max_open) # type: ignore[arg-type]599 return self._clamp(max, -1, self.max_open)600601 if lt_min or gt_max:602 self.fail(603 _("{value} is not in the range {range}.").format(
6 unmodified lines
610 return rv611612 @abc.abstractmethod613 def _clamp(591 self, bound: ParamTypeValue, dir: t.Literal[1, -1], open: bool592 ) -> ParamTypeValue:614 # Covariant type variables cannot be used in input positions, so we use a615 # separate method-scoped type variable instead.616 self: _NumberRangeBase[t.Any, _FloatValueT],617 bound: _FloatValueT,618 dir: t.Literal[1, -1],619 open: bool,620 ) -> _FloatValueT:621 """Find the valid value to clamp to bound in the given622 direction.623624 :param bound: The boundary value.
20 unmodified lines
645 clamp = " clamped" if self.clamp else ""646 return f"<{type(self).__name__} {self._describe_range()}{clamp}>"647648621class IntParamType(_NumberParamTypeBase[int]):649class IntParamType(_NumberParamTypeBase[t.SupportsInt | t.SupportsIndex, int]):650 name = "integer"651 _number_class = int652653 def __repr__(self) -> str:654 return "INT"655656629class IntRange(_NumberRangeBase[int], IntParamType):657class IntRange(_NumberRangeBase[int, int], IntParamType):658 """Restrict an :data:`click.INT` value to a range of accepted659 values. See :ref:`ranges`.660661 If ``min`` or ``max`` are not passed, any value is accepted in that
15 unmodified lines
677678 return bound + dir679680653class FloatParamType(_NumberParamTypeBase[float]):681class FloatParamType(_NumberParamTypeBase[t.SupportsFloat | t.SupportsIndex, float]):682 name = "float"683 _number_class = float684685 def __repr__(self) -> str:686 return "FLOAT"687688661class FloatRange(_NumberRangeBase[float], FloatParamType):689class FloatRange(_NumberRangeBase[float, float], FloatParamType):690 """Restrict a :data:`click.FLOAT` value to a range of accepted691 values. See :ref:`ranges`.692693 If ``min`` or ``max`` are not passed, any value is accepted in that
107 unmodified lines
801class UUIDParameterType(ParamType[uuid.UUID]):802 name = "uuid"803804 def convert(777 self, value: t.Any, param: Parameter | None, ctx: Context | None805 self, value: uuid.UUID | str, param: Parameter | None, ctx: Context | None806 ) -> uuid.UUID:807 if isinstance(value, uuid.UUID):808 return value809
47 unmodified lines
857858 name = "filename"859 envvar_list_splitter: t.ClassVar[str] = os.path.pathsep860861 mode: str862 encoding: str | None863 errors: str | None864 lazy: bool | None865 atomic: bool866867 def __init__(868 self,869 mode: str = "r",870 encoding: str | None = None,
31 unmodified lines
902 ) -> t.IO[t.Any]:903 if _is_file_like(value):904 return value905872 value = t.cast("str | os.PathLike[str]", value)873906 try:907 lazy = self.resolve_lazy_flag(value)908909 if lazy:
45 unmodified lines
955956 return [CompletionItem(incomplete, type="file")]957958927def _is_file_like(value: t.Any) -> te.TypeGuard[t.IO[t.Any]]:959def _is_file_like(value: t.Any) -> te.TypeIs[t.IO[t.Any]]:960 return hasattr(value, "read") or hasattr(value, "write")961962963class PathInfoDict(ParamTypeInfoDict):
39 unmodified lines
1003 """10041005 envvar_list_splitter: t.ClassVar[str] = os.path.pathsep10061007 exists: bool1008 file_okay: bool1009 dir_okay: bool1010 readable: bool1011 writable: bool1012 executable: bool1013 resolve_path: bool1014 allow_dash: bool1015 name: str10161017 def __init__(1018 self,1019 exists: bool = False,1020 file_okay: bool = True,
1 unmodified line
1022 writable: bool = False,1023 readable: bool = True,1024 resolve_path: bool = False,1025 allow_dash: bool = False,984 path_type: type[t.Any] | None = None,1026 path_type: type | None = None,1027 executable: bool = False,986 ):1028 ) -> None:1029 self.exists = exists1030 self.file_okay = file_okay1031 self.dir_okay = dir_okay1032 self.readable = readable1033 self.writable = writable1034 self.executable = executable1035 self.resolve_path = resolve_path1036 self.allow_dash = allow_dash995 self.type = path_type1037 self.type: type | None = path_type10381039 if self.file_okay and not self.dir_okay:998 self.name: str = _("file")1040 self.name = _("file")1041 elif self.dir_okay and not self.file_okay:1042 self.name = _("directory")1043 else:1044 self.name = _("path")
207 unmodified lines
125212531254@t.overload1255def convert_type(ty: None, default: None = None) -> StringParamType: ...121412151256@t.overload1257def convert_type(1218 ty: type[t.Any] | ParamType[t.Any], default: t.Any | None = None1258 ty: type | ParamType[t.Any], default: t.Any | None = None1259) -> ParamType[t.Any]: ...122012211260@t.overload1261def convert_type(1262 ty: t.Any | None, default: t.Any | None = None1263) -> ParamType[t.Any]: ...122612271264def convert_type(1265 ty: t.Any | None = None, default: t.Any | None = None1266) -> ParamType[t.Any]:1267 """Find the most appropriate :class:`ParamType` for the given Python
47 unmodified lines
1315#: there are situations where an unprocessed type is useful which is why1316#: it is provided.1317#:1318#: .. versionadded:: 4.01283UNPROCESSED = UnprocessedParamType()1319UNPROCESSED: t.Final[UnprocessedParamType] = UnprocessedParamType()13201321#: A unicode string parameter type which is the implicit default. This1322#: can also be selected by using ``str`` as type.1287STRING = StringParamType()1323STRING: t.Final[StringParamType] = StringParamType()13241325#: An integer parameter. This can also be selected by using ``int`` as1326#: type.1291INT = IntParamType()1327INT: t.Final[IntParamType] = IntParamType()13281329#: A floating point value parameter. This can also be selected by using1330#: ``float`` as type.1295FLOAT = FloatParamType()1331FLOAT: t.Final[FloatParamType] = FloatParamType()13321333#: A boolean parameter. This is the default for boolean flags. This can1334#: also be selected by using ``bool`` as a type.1299BOOL = BoolParamType()1335BOOL: t.Final[BoolParamType] = BoolParamType()13361337#: A UUID parameter.1302UUID = UUIDParameterType()1338UUID: t.Final[UUIDParameterType] = UUIDParameterType()133913401341class OptionHelpExtra(t.TypedDict, total=False):1342 envvars: tuple[str, ...]
3 unmodified lines