`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
Provenance
- Commit
77bd81f- Tree
97abd77- Author
jorenham <jhammudoglu@gmail.com>- Committer
jorenham <jhammudoglu@gmail.com>- Parent
648d7c4
1 file changed+117 added−81 removed
modified:src/click/types.py+117 added-81 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+class FuncParamTypeInfoDict(ParamTypeInfoDict, t.Generic[_ValueT_contra, _ValueT_co]):193+ func: t.Callable[[_ValueT_contra], _ValueT_co]194 195 191-class FuncParamType(ParamType[ParamTypeValue]):192- def __init__(self, func: t.Callable[[t.Any], ParamTypeValue]) -> None:193- self.name: str = func.__name__196+class FuncParamType(ParamType[_ValueT_co], t.Generic[_ValueT_contra, _ValueT_co]):197+ name: str198+ func: t.Callable[[_ValueT_contra], _ValueT_co]199+200+ def __init__(self, func: t.Callable[[_ValueT_contra], _ValueT_co]) -> None:201+ self.name = func.__name__202 self.func = func203 196- 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()}206 207 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 line215 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")220 221 self.fail(message, param, ctx)222 223 224 class UnprocessedParamType(ParamType[t.Any]):225 name = "text"226 227 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 value231 232 def __repr__(self) -> str:233 return "UNPROCESSED"7 unmodified lines241 ) -> 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)256 257 def __repr__(self) -> str:258 return "STRING"259 260 254-class ChoiceInfoDict(ParamTypeInfoDict):255- choices: cabc.Sequence[t.Any]261+class ChoiceInfoDict(ParamTypeInfoDict, t.Generic[_ValueT_co]):262+ choices: tuple[_ValueT_co, ...]263 case_sensitive: bool264 265 259-class Choice(ParamType[ParamTypeValue], t.Generic[ParamTypeValue]):266+class 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.269 270 You may pass any iterable value which will be converted to a tuple19 unmodified lines290 .. versionadded:: 8.2.0291 Choice normalization can be overridden via :meth:`normalize_choice`.292 """293 287- name = "choice"294+ name: str = "choice"295 296+ choices: tuple[_ValueT_co, ...]297+ case_sensitive: bool298+299 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_sensitive304 295- 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 }311 312 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 lines326 )327 for choice in self.choices328 }329 320- 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 lines347 348 return normed_value349 350 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 lines376 )377 378 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 lines465 """466 467 name = "datetime"468 469+ formats: cabc.Sequence[str]470+471 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 ]477 478 def to_info_dict(self) -> DateTimeInfoDict:479 return {"formats": self.formats, **super().to_info_dict()}480 469- 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)}]"483 484 def _try_to_convert_date(self, value: t.Any, format: str) -> datetime | None:485 try:27 unmodified lines513 def __repr__(self) -> str:514 return "DateTime"515 516 505-class _NumberParamTypeBase(ParamType[ParamTypeValue]):506- _number_class: t.Callable[[t.Any], ParamTypeValue]517+class _NumberParamTypeBase(518+ ParamType[_ValueT_co], t.Generic[_ValueT_contra, _ValueT_co]519+):520+ _number_class: t.Callable[[_ValueT_contra], _ValueT_co]521 522 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 lines533 ctx,534 )535 536 523-class NumberRangeInfoDict(ParamTypeInfoDict):524- min: float | None525- max: float | None537+class NumberRangeInfoDict(ParamTypeInfoDict, t.Generic[_FloatValueT_co]):538+ min: _FloatValueT_co | None539+ max: _FloatValueT_co | None540 min_open: bool541 max_open: bool542 clamp: bool543 544 531-class _NumberRangeBase(_NumberParamTypeBase[ParamTypeValue]):545+class _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: bool554+555 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 lines565 self.min_open = min_open566 self.max_open = max_open567 self.clamp = clamp568 546- 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 lines576 **super().to_info_dict(),577 }578 579 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 operator583 584 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)593 594 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)597 598 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)600 601 if lt_min or gt_max:602 self.fail(603 _("{value} is not in the range {range}.").format(6 unmodified lines610 return rv611 612 @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.623 624 :param bound: The boundary value.20 unmodified lines645 clamp = " clamped" if self.clamp else ""646 return f"<{type(self).__name__} {self._describe_range()}{clamp}>"647 648 621-class IntParamType(_NumberParamTypeBase[int]):649+class IntParamType(_NumberParamTypeBase[t.SupportsInt | t.SupportsIndex, int]):650 name = "integer"651 _number_class = int652 653 def __repr__(self) -> str:654 return "INT"655 656 629-class IntRange(_NumberRangeBase[int], IntParamType):657+class IntRange(_NumberRangeBase[int, int], IntParamType):658 """Restrict an :data:`click.INT` value to a range of accepted659 values. See :ref:`ranges`.660 661 If ``min`` or ``max`` are not passed, any value is accepted in that15 unmodified lines677 678 return bound + dir679 680 653-class FloatParamType(_NumberParamTypeBase[float]):681+class FloatParamType(_NumberParamTypeBase[t.SupportsFloat | t.SupportsIndex, float]):682 name = "float"683 _number_class = float684 685 def __repr__(self) -> str:686 return "FLOAT"687 688 661-class FloatRange(_NumberRangeBase[float], FloatParamType):689+class FloatRange(_NumberRangeBase[float, float], FloatParamType):690 """Restrict a :data:`click.FLOAT` value to a range of accepted691 values. See :ref:`ranges`.692 693 If ``min`` or ``max`` are not passed, any value is accepted in that107 unmodified lines801 class UUIDParameterType(ParamType[uuid.UUID]):802 name = "uuid"803 804 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 lines857 858 name = "filename"859 envvar_list_splitter: t.ClassVar[str] = os.path.pathsep860 861+ mode: str862+ encoding: str | None863+ errors: str | None864+ lazy: bool | None865+ atomic: bool866+867 def __init__(868 self,869 mode: str = "r",870 encoding: str | None = None,31 unmodified lines902 ) -> t.IO[t.Any]:903 if _is_file_like(value):904 return value905 872- value = t.cast("str | os.PathLike[str]", value)873-906 try:907 lazy = self.resolve_lazy_flag(value)908 909 if lazy:45 unmodified lines955 956 return [CompletionItem(incomplete, type="file")]957 958 927-def _is_file_like(value: t.Any) -> te.TypeGuard[t.IO[t.Any]]:959+def _is_file_like(value: t.Any) -> te.TypeIs[t.IO[t.Any]]:960 return hasattr(value, "read") or hasattr(value, "write")961 962 963 class PathInfoDict(ParamTypeInfoDict):39 unmodified lines1003 """1004 1005 envvar_list_splitter: t.ClassVar[str] = os.path.pathsep1006 1007+ exists: bool1008+ file_okay: bool1009+ dir_okay: bool1010+ readable: bool1011+ writable: bool1012+ executable: bool1013+ resolve_path: bool1014+ allow_dash: bool1015+ name: str1016+1017 def __init__(1018 self,1019 exists: bool = False,1020 file_okay: bool = True,1 unmodified line1022 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_type1038 1039 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 lines1252 1253 1254 @t.overload1255 def convert_type(ty: None, default: None = None) -> StringParamType: ...1214-1215-1256 @t.overload1257 def 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]: ...1220-1221-1260 @t.overload1261 def convert_type(1262 ty: t.Any | None, default: t.Any | None = None1263 ) -> ParamType[t.Any]: ...1226-1227-1264 def 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 Python47 unmodified lines1315 #: there are situations where an unprocessed type is useful which is why1316 #: it is provided.1317 #:1318 #: .. versionadded:: 4.01283-UNPROCESSED = UnprocessedParamType()1319+UNPROCESSED: t.Final[UnprocessedParamType] = UnprocessedParamType()1320 1321 #: A unicode string parameter type which is the implicit default. This1322 #: can also be selected by using ``str`` as type.1287-STRING = StringParamType()1323+STRING: t.Final[StringParamType] = StringParamType()1324 1325 #: An integer parameter. This can also be selected by using ``int`` as1326 #: type.1291-INT = IntParamType()1327+INT: t.Final[IntParamType] = IntParamType()1328 1329 #: A floating point value parameter. This can also be selected by using1330 #: ``float`` as type.1295-FLOAT = FloatParamType()1331+FLOAT: t.Final[FloatParamType] = FloatParamType()1332 1333 #: A boolean parameter. This is the default for boolean flags. This can1334 #: also be selected by using ``bool`` as a type.1299-BOOL = BoolParamType()1335+BOOL: t.Final[BoolParamType] = BoolParamType()1336 1337 #: A UUID parameter.1302-UUID = UUIDParameterType()1338+UUID: t.Final[UUIDParameterType] = UUIDParameterType()1339 1340 1341 class OptionHelpExtra(t.TypedDict, total=False):1342 envvars: tuple[str, ...]3 unmodified lines