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
Provenance
- Commit
dcdca58- Tree
9b13651- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
6c3a1fc- Parent 2
9149ebc
10 files changed+77 added−39 removed
modified:src/click/_compat.py+1 added-1 removed
365 unmodified lines366 return _force_correct_text_writer(sys.stderr, encoding, errors, force_writable=True)367 368 369 def _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 linesmodified:src/click/_termui_impl.py+17 added-9 removed
8 unmodified lines9 import sys10 import time11 import typing as t12 from gettext import gettext as _13+from types import TracebackType14 15 from ._compat import _default_text_stdout16 from ._compat import CYGWIN17 from ._compat import get_best_encoding41 unmodified lines59 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 == 072 73 if length is None:74 from operator import length_hint75 4 unmodified lines80 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] = None98 99 def __enter__(self) -> "ProgressBar[V]":100 self.entered = True101 self.render_progress()102 return self103 101- 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()111 112 def __iter__(self) -> t.Iterator[V]:113 if not self.entered:612 unmodified linesmodified:src/click/core.py+19 added-9 removed
5 unmodified lines6 import typing as t7 from collections import abc8 from contextlib import contextmanager9 from contextlib import ExitStack10-from functools import partial10 from functools import update_wrapper11 from gettext import gettext as _12 from gettext import ngettext13 from itertools import repeat14+from types import TracebackType15 16 from . import types17 from .exceptions import Abort18 from .exceptions import BadParameter435 unmodified lines454 self._depth += 1455 push_context(self)456 return self457 458- 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 lines2101 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)2112 2113 # Default nargs to what the type tells us if we have that2114 # information available.2115 if nargs is None:191 unmodified lines2307 _("Value must be an iterable."), ctx=ctx, param=self2308 ) from None2309 2310 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- )2311+2312+ def convert(value: t.Any) -> t.Any:2313+ return self.type(value, param=self, ctx=ctx)2314+2315 elif self.nargs == -1:2316 2308- 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))2319 2320 else: # nargs > 12321 2313- 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))2324 2325 if len(value) != self.nargs:2326 raise BadParameter(245 unmodified lines2572 2573 if flag_value is None:2574 flag_value = not self.default2575 2576+ 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)2581 2582 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_value2585 2586 # Counting2587 self.count = count450 unmodified linesmodified:src/click/exceptions.py+4 added-3 removed
5 unmodified lines6 from ._compat import get_text_stderr7 from .utils import echo8 9 if t.TYPE_CHECKING:10+ from .core import Command11 from .core import Context12 from .core import Parameter13 14 42 unmodified lines57 58 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 None62 63 def show(self, file: t.Optional[t.IO[t.Any]] = None) -> None:64 if file is None:65 file = get_text_stderr()195 unmodified lines261 if hint is None:262 hint = _("unknown error")263 264 super().__init__(hint)264- self.ui_filename = os.fsdecode(filename)265+ self.ui_filename: str = os.fsdecode(filename)266 self.filename = filename267 268 def format_message(self) -> str:269 return _("Could not open file {filename!r}: {message}").format(14 unmodified lines284 285 __slots__ = ("exit_code",)286 287 def __init__(self, code: int = 0) -> None:287- self.exit_code = code288+ self.exit_code: int = codemodified:src/click/parser.py+4 added-4 removed
166 unmodified lines167 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()172 173 for opt in opts:174 prefix, value = split_opt(opt)175 if not prefix:17 unmodified lines193 @property194 def takes_value(self) -> bool:195 return self.action in ("store", "append")196 197- 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: ignore69 unmodified lines271 #: 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 = False281 282 if ctx is not None:283 self.allow_interspersed_args = ctx.allow_interspersed_args284 self.ignore_unknown_options = ctx.ignore_unknown_options245 unmodified linesmodified:src/click/shell_completion.py+5 added-3 removed
78 unmodified lines79 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 = kwargs87 88 def __getattr__(self, name: str) -> t.Any:89 return self._info.get(name)426 unmodified lines516 517 ctx = cmd.make_context(name, args, parent=ctx, resilient_parsing=True)518 args = ctx.protected_args + ctx.args519 else:520+ sub_ctx = ctx521+522 while args:523 name, cmd, args = command.resolve_command(ctx, args)524 525 if cmd is None:65 unmodified linesmodified:src/click/testing.py+1 added-1 removed
181 unmodified lines182 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_stderr189 190 def get_default_prog_name(self, cli: "BaseCommand") -> str:289 unmodified linesmodified:src/click/types.py+10 added-6 removed
160 unmodified lines161 162 163 class 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 = func167 168 def to_info_dict(self) -> t.Dict[str, t.Any]:169 info_dict = super().to_info_dict()182 unmodified lines352 353 name = "datetime"354 355 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+ ]361 362 def to_info_dict(self) -> t.Dict[str, t.Any]:363 info_dict = super().to_info_dict()364 info_dict["formats"] = self.formats300 unmodified lines665 See :ref:`file-args` for more information.666 """667 668 name = "filename"665- envvar_list_splitter = os.path.pathsep669+ envvar_list_splitter: t.ClassVar[str] = os.path.pathsep670 671 def __init__(672 self,673 mode: str = "r",109 unmodified lines783 .. versionchanged:: 6.0784 Added the ``allow_dash`` parameter.785 """786 783- envvar_list_splitter = os.path.pathsep787+ envvar_list_splitter: t.ClassVar[str] = os.path.pathsep788 789 def __init__(790 self,791 exists: bool = False,16 unmodified lines808 self.allow_dash = allow_dash809 self.type = path_type810 811 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 lines945 :param types: a list of types that should be used for the tuple items.946 """947 948 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]950 951 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 linesmodified:src/click/utils.py+15 added-3 removed
2 unmodified lines3 import sys4 import typing as t5 from functools import update_wrapper6 from types import ModuleType7+from types import TracebackType8 9 from ._compat import _default_text_stderr10 from ._compat import _default_text_stdout11 from ._compat import _find_binary_writer112 unmodified lines124 self.encoding = encoding125 self.errors = errors126 self.atomic = atomic127 self._f: t.Optional[t.IO[t.Any]]128+ self.should_close: bool129 130 if filename == "-":131 self._f, self.should_close = open_stream(filename, mode, encoding, errors)132 else:45 unmodified lines178 179 def __enter__(self) -> "LazyFile":180 return self181 180- 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()189 190 def __iter__(self) -> t.Iterator[t.AnyStr]:191 self.open()1 unmodified line193 194 195 class KeepOpenFile:196 def __init__(self, file: t.IO[t.Any]) -> None:190- self._file = file197+ self._file: t.IO[t.Any] = file198 199 def __getattr__(self, name: str) -> t.Any:200 return getattr(self._file, name)201 202 def __enter__(self) -> "KeepOpenFile":203 return self204 198- 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 pass212 213 def __repr__(self) -> str:214 return repr(self._file)383 unmodified linesmodified:CHANGES.rst+1 added
11 unmodified lines12 - 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`17 18 19 Version 8.1.320 -------------1040 unmodified lines