Skip to content
Myr

update types to pass `pyright --verifytypes click` (#2269)

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

authored by David Lord · committed by GitHub · parents 6c3a1fc, 9149ebc · Browse files · 10 files+77 added−39 removed
This commit

State

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

Diff stats

10 files+77 added−39 removed

  • other:+77 added−39 removed

10 files+77 added−39 removed

modified:src/click/_compat.py+1 added-1 removed
365 unmodified lines
366 return _force_correct_text_writer(sys.stderr, encoding, errors, force_writable=True)367368369def _wrap_io_open(370 file: t.Union[str, "os.PathLike[t.AnyStr]", int],370 file: t.Union[str, "os.PathLike[str]", int],371 mode: str,372 encoding: t.Optional[str],373 errors: t.Optional[str],374) -> t.IO[t.Any]:
252 unmodified lines
modified:src/click/_termui_impl.py+17 added-9 removed
8 unmodified lines
9import sys10import time11import typing as t12from gettext import gettext as _13from types import TracebackType1415from ._compat import _default_text_stdout16from ._compat import CYGWIN17from ._compat import get_best_encoding
41 unmodified lines
59 self.show_eta = show_eta60 self.show_percent = show_percent61 self.show_pos = show_pos62 self.item_show_func = item_show_func62 self.label = label or ""63 self.label: str = label or ""64 if file is None:65 file = _default_text_stdout()66 self.file = file67 self.color = color68 self.update_min_steps = update_min_steps69 self._completed_intervals = 069 self.width = width70 self.autowidth = width == 070 self.width: int = width71 self.autowidth: bool = width == 07273 if length is None:74 from operator import length_hint75
4 unmodified lines
80 if iterable is None:81 if length is None:82 raise TypeError("iterable or length is required")83 iterable = t.cast(t.Iterable[V], range(length))83 self.iter = iter(iterable)84 self.iter: t.Iterable[V] = iter(iterable)85 self.length = length86 self.pos = 087 self.avg: t.List[float] = []88 self.last_eta: float89 self.start: float90 self.start = self.last_eta = time.time()88 self.eta_known = False89 self.finished = False91 self.eta_known: bool = False92 self.finished: bool = False93 self.max_width: t.Optional[int] = None91 self.entered = False94 self.entered: bool = False95 self.current_item: t.Optional[V] = None93 self.is_hidden = not isatty(self.file)96 self.is_hidden: bool = not isatty(self.file)97 self._last_line: t.Optional[str] = None9899 def __enter__(self) -> "ProgressBar[V]":100 self.entered = True101 self.render_progress()102 return self103101 def __exit__(self, *_: t.Any) -> None:104 def __exit__(105 self,106 exc_type: t.Optional[t.Type[BaseException]],107 exc_value: t.Optional[BaseException],108 tb: t.Optional[TracebackType],109 ) -> None:110 self.render_finish()111112 def __iter__(self) -> t.Iterator[V]:113 if not self.entered:
612 unmodified lines
modified:src/click/core.py+19 added-9 removed
5 unmodified lines
6import typing as t7from collections import abc8from contextlib import contextmanager9from contextlib import ExitStack10from functools import partial10from functools import update_wrapper11from gettext import gettext as _12from gettext import ngettext13from itertools import repeat14from types import TracebackType1516from . import types17from .exceptions import Abort18from .exceptions import BadParameter
435 unmodified lines
454 self._depth += 1455 push_context(self)456 return self457458 def __exit__(self, *_: t.Any) -> None:458 def __exit__(459 self,460 exc_type: t.Optional[t.Type[BaseException]],461 exc_value: t.Optional[BaseException],462 tb: t.Optional[TracebackType],463 ) -> None:464 self._depth -= 1465 if self._depth == 0:466 self.close()467 pop_context()
1633 unmodified lines
2101 t.Union[t.List["CompletionItem"], t.List[str]],2102 ]2103 ] = None,2104 ) -> None:2105 self.name: t.Optional[str]2106 self.opts: t.List[str]2107 self.secondary_opts: t.List[str]2108 self.name, self.opts, self.secondary_opts = self._parse_decls(2109 param_decls or (), expose_value2110 )2103 self.type = types.convert_type(type, default)2111 self.type: types.ParamType = types.convert_type(type, default)21122113 # Default nargs to what the type tells us if we have that2114 # information available.2115 if nargs is None:
191 unmodified lines
2307 _("Value must be an iterable."), ctx=ctx, param=self2308 ) from None23092310 if self.nargs == 1 or self.type.is_composite:2303 convert: t.Callable[[t.Any], t.Any] = partial(2304 self.type, param=self, ctx=ctx2305 )23112312 def convert(value: t.Any) -> t.Any:2313 return self.type(value, param=self, ctx=ctx)23142315 elif self.nargs == -1:23162308 def convert(value: t.Any) -> t.Tuple[t.Any, ...]:2317 def convert(value: t.Any) -> t.Any: # t.Tuple[t.Any, ...]2318 return tuple(self.type(x, self, ctx) for x in check_iter(value))23192320 else: # nargs > 123212313 def convert(value: t.Any) -> t.Tuple[t.Any, ...]:2322 def convert(value: t.Any) -> t.Any: # t.Tuple[t.Any, ...]2323 value = tuple(check_iter(value))23242325 if len(value) != self.nargs:2326 raise BadParameter(
245 unmodified lines
25722573 if flag_value is None:2574 flag_value = not self.default25752576 self.type: types.ParamType2577 if is_flag and type is None:2578 # Re-guess the type from the flag value instead of the2579 # default.2580 self.type = types.convert_type(None, flag_value)25812582 self.is_flag: bool = is_flag2573 self.is_bool_flag = is_flag and isinstance(self.type, types.BoolParamType)2583 self.is_bool_flag: bool = is_flag and isinstance(self.type, types.BoolParamType)2584 self.flag_value: t.Any = flag_value25852586 # Counting2587 self.count = count
450 unmodified lines
modified:src/click/exceptions.py+4 added-3 removed
5 unmodified lines
6from ._compat import get_text_stderr7from .utils import echo89if t.TYPE_CHECKING:10 from .core import Command11 from .core import Context12 from .core import Parameter1314
42 unmodified lines
5758 def __init__(self, message: str, ctx: t.Optional["Context"] = None) -> None:59 super().__init__(message)60 self.ctx = ctx60 self.cmd = self.ctx.command if self.ctx else None61 self.cmd: t.Optional["Command"] = self.ctx.command if self.ctx else None6263 def show(self, file: t.Optional[t.IO[t.Any]] = None) -> None:64 if file is None:65 file = get_text_stderr()
195 unmodified lines
261 if hint is None:262 hint = _("unknown error")263264 super().__init__(hint)264 self.ui_filename = os.fsdecode(filename)265 self.ui_filename: str = os.fsdecode(filename)266 self.filename = filename267268 def format_message(self) -> str:269 return _("Could not open file {filename!r}: {message}").format(
14 unmodified lines
284285 __slots__ = ("exit_code",)286287 def __init__(self, code: int = 0) -> None:287 self.exit_code = code288 self.exit_code: int = code
modified:src/click/parser.py+4 added-4 removed
166 unmodified lines
167 const: t.Optional[t.Any] = None,168 ):169 self._short_opts = []170 self._long_opts = []171 self.prefixes = set()171 self.prefixes: t.Set[str] = set()172173 for opt in opts:174 prefix, value = split_opt(opt)175 if not prefix:
17 unmodified lines
193 @property194 def takes_value(self) -> bool:195 return self.action in ("store", "append")196197 def process(self, value: str, state: "ParsingState") -> None:197 def process(self, value: t.Any, state: "ParsingState") -> None:198 if self.action == "store":199 state.opts[self.dest] = value # type: ignore200 elif self.action == "store_const":201 state.opts[self.dest] = self.const # type: ignore
69 unmodified lines
271 #: This controls how the parser deals with interspersed arguments.272 #: If this is set to `False`, the parser will stop on the first273 #: non-option. Click uses this to implement nested subcommands274 #: safely.275 self.allow_interspersed_args = True275 self.allow_interspersed_args: bool = True276 #: This tells the parser how to deal with unknown options. By277 #: default it will error out (which is sensible), but there is a278 #: second mode where it will ignore it and continue processing279 #: after shifting all the unknown options into the resulting args.280 self.ignore_unknown_options = False280 self.ignore_unknown_options: bool = False281282 if ctx is not None:283 self.allow_interspersed_args = ctx.allow_interspersed_args284 self.ignore_unknown_options = ctx.ignore_unknown_options
245 unmodified lines
modified:src/click/shell_completion.py+5 added-3 removed
78 unmodified lines
79 type: str = "plain",80 help: t.Optional[str] = None,81 **kwargs: t.Any,82 ) -> None:83 self.value = value84 self.type = type85 self.help = help83 self.value: t.Any = value84 self.type: str = type85 self.help: t.Optional[str] = help86 self._info = kwargs8788 def __getattr__(self, name: str) -> t.Any:89 return self._info.get(name)
426 unmodified lines
516517 ctx = cmd.make_context(name, args, parent=ctx, resilient_parsing=True)518 args = ctx.protected_args + ctx.args519 else:520 sub_ctx = ctx521522 while args:523 name, cmd, args = command.resolve_command(ctx, args)524525 if cmd is None:
65 unmodified lines
modified:src/click/testing.py+1 added-1 removed
181 unmodified lines
182 echo_stdin: bool = False,183 mix_stderr: bool = True,184 ) -> None:185 self.charset = charset186 self.env = env or {}186 self.env: t.Mapping[str, t.Optional[str]] = env or {}187 self.echo_stdin = echo_stdin188 self.mix_stderr = mix_stderr189190 def get_default_prog_name(self, cli: "BaseCommand") -> str:
289 unmodified lines
modified:src/click/types.py+10 added-6 removed
160 unmodified lines
161162163class FuncParamType(ParamType):164 def __init__(self, func: t.Callable[[t.Any], t.Any]) -> None:165 self.name = func.__name__165 self.name: str = func.__name__166 self.func = func167168 def to_info_dict(self) -> t.Dict[str, t.Any]:169 info_dict = super().to_info_dict()
182 unmodified lines
352353 name = "datetime"354355 def __init__(self, formats: t.Optional[t.Sequence[str]] = None):356 self.formats = formats or ["%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S"]356 self.formats: t.Sequence[str] = formats or [357 "%Y-%m-%d",358 "%Y-%m-%dT%H:%M:%S",359 "%Y-%m-%d %H:%M:%S",360 ]361362 def to_info_dict(self) -> t.Dict[str, t.Any]:363 info_dict = super().to_info_dict()364 info_dict["formats"] = self.formats
300 unmodified lines
665 See :ref:`file-args` for more information.666 """667668 name = "filename"665 envvar_list_splitter = os.path.pathsep669 envvar_list_splitter: t.ClassVar[str] = os.path.pathsep670671 def __init__(672 self,673 mode: str = "r",
109 unmodified lines
783 .. versionchanged:: 6.0784 Added the ``allow_dash`` parameter.785 """786783 envvar_list_splitter = os.path.pathsep787 envvar_list_splitter: t.ClassVar[str] = os.path.pathsep788789 def __init__(790 self,791 exists: bool = False,
16 unmodified lines
808 self.allow_dash = allow_dash809 self.type = path_type810811 if self.file_okay and not self.dir_okay:808 self.name = _("file")812 self.name: str = _("file")813 elif self.dir_okay and not self.file_okay:814 self.name = _("directory")815 else:816 self.name = _("path")
128 unmodified lines
945 :param types: a list of types that should be used for the tuple items.946 """947948 def __init__(self, types: t.Sequence[t.Union[t.Type[t.Any], ParamType]]) -> None:945 self.types = [convert_type(ty) for ty in types]949 self.types: t.Sequence[ParamType] = [convert_type(ty) for ty in types]950951 def to_info_dict(self) -> t.Dict[str, t.Any]:952 info_dict = super().to_info_dict()953 info_dict["types"] = [t.to_info_dict() for t in self.types]
121 unmodified lines
modified:src/click/utils.py+15 added-3 removed
2 unmodified lines
3import sys4import typing as t5from functools import update_wrapper6from types import ModuleType7from types import TracebackType89from ._compat import _default_text_stderr10from ._compat import _default_text_stdout11from ._compat import _find_binary_writer
112 unmodified lines
124 self.encoding = encoding125 self.errors = errors126 self.atomic = atomic127 self._f: t.Optional[t.IO[t.Any]]128 self.should_close: bool129130 if filename == "-":131 self._f, self.should_close = open_stream(filename, mode, encoding, errors)132 else:
45 unmodified lines
178179 def __enter__(self) -> "LazyFile":180 return self181180 def __exit__(self, *_: t.Any) -> None:182 def __exit__(183 self,184 exc_type: t.Optional[t.Type[BaseException]],185 exc_value: t.Optional[BaseException],186 tb: t.Optional[TracebackType],187 ) -> None:188 self.close_intelligently()189190 def __iter__(self) -> t.Iterator[t.AnyStr]:191 self.open()
1 unmodified line
193194195class KeepOpenFile:196 def __init__(self, file: t.IO[t.Any]) -> None:190 self._file = file197 self._file: t.IO[t.Any] = file198199 def __getattr__(self, name: str) -> t.Any:200 return getattr(self._file, name)201202 def __enter__(self) -> "KeepOpenFile":203 return self204198 def __exit__(self, *_: t.Any) -> None:205 def __exit__(206 self,207 exc_type: t.Optional[t.Type[BaseException]],208 exc_value: t.Optional[BaseException],209 tb: t.Optional[TracebackType],210 ) -> None:211 pass212213 def __repr__(self) -> str:214 return repr(self._file)
383 unmodified lines
modified:CHANGES.rst+1 added
11 unmodified lines
12- Fix return value and type signature of `shell_completion.add_completion_class`13 function. :pr:`2421`14- Bash version detection doesn't fail on Windows. :issue:`2461`15- Completion works if there is a dot (``.``) in the program name. :issue:`2166`16- Improve type annotations for pyright type checker. :issue:`2268`171819Version 8.1.320-------------
1040 unmodified lines