Types: don't leave generic types without a parameter (#2401)
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 a6c7ee0, 9afe27e · Browse files · 10 files·+197 added−112 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+197 added−112 removed
- other:+197 added−112 removed
Provenance
- Commit
c0092d2- Tree
13edb45- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
a6c7ee0- Parent 2
9afe27e
10 files changed+197 added−112 removed
modified:src/click/_compat.py+19 added-19 removed
48 unmodified lines49 except LookupError:50 return False51 52 53-def get_best_encoding(stream: t.IO) -> str:53+def get_best_encoding(stream: t.IO[t.Any]) -> str:54 """Returns the default stream encoding if not found."""55 rv = getattr(stream, "encoding", None) or sys.getdefaultencoding()56 if is_ascii_encoding(rv):57 return "utf-8"94 unmodified lines152 return False153 return True154 155 156-def _is_binary_reader(stream: t.IO, default: bool = False) -> bool:156+def _is_binary_reader(stream: t.IO[t.Any], default: bool = False) -> bool:157 try:158 return isinstance(stream.read(0), bytes)159 except Exception:160 return default161 # This happens in some cases where the stream was already162 # closed. In this case, we assume the default.163 164 165-def _is_binary_writer(stream: t.IO, default: bool = False) -> bool:165+def _is_binary_writer(stream: t.IO[t.Any], default: bool = False) -> bool:166 try:167 stream.write(b"")168 except Exception:169 try:4 unmodified lines174 return default175 return True176 177 178-def _find_binary_reader(stream: t.IO) -> t.Optional[t.BinaryIO]:178+def _find_binary_reader(stream: t.IO[t.Any]) -> t.Optional[t.BinaryIO]:179 # We need to figure out if the given stream is already binary.180 # This can happen because the official docs recommend detaching181 # the streams to get binary streams. Some code might do this, so182 # we need to deal with this case explicitly.9 unmodified lines192 193 return None194 195 196-def _find_binary_writer(stream: t.IO) -> t.Optional[t.BinaryIO]:196+def _find_binary_writer(stream: t.IO[t.Any]) -> t.Optional[t.BinaryIO]:197 # We need to figure out if the given stream is already binary.198 # This can happen because the official docs recommend detaching199 # the streams to get binary streams. Some code might do this, so200 # we need to deal with this case explicitly.39 unmodified lines240 ) and _is_compat_stream_attr(stream, "errors", errors)241 242 243 def _force_correct_text_stream(244- text_stream: t.IO,244+ text_stream: t.IO[t.Any],245 encoding: t.Optional[str],246 errors: t.Optional[str],247- is_binary: t.Callable[[t.IO, bool], bool],248- find_binary: t.Callable[[t.IO], t.Optional[t.BinaryIO]],247+ is_binary: t.Callable[[t.IO[t.Any], bool], bool],248+ find_binary: t.Callable[[t.IO[t.Any]], t.Optional[t.BinaryIO]],249 force_readable: bool = False,250 force_writable: bool = False,251 ) -> t.TextIO:252 if is_binary(text_stream, False):33 unmodified lines286 )287 288 289 def _force_correct_text_reader(290- text_reader: t.IO,290+ text_reader: t.IO[t.Any],291 encoding: t.Optional[str],292 errors: t.Optional[str],293 force_readable: bool = False,294 ) -> t.TextIO:7 unmodified lines302 )303 304 305 def _force_correct_text_writer(306- text_writer: t.IO,306+ text_writer: t.IO[t.Any],307 encoding: t.Optional[str],308 errors: t.Optional[str],309 force_writable: bool = False,310 ) -> t.TextIO:55 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, int],370+ file: t.Union[str, "os.PathLike[t.AnyStr]", int],371 mode: str,372 encoding: t.Optional[str],373 errors: t.Optional[str],374-) -> t.IO:374+) -> t.IO[t.Any]:375 """Handles not passing ``encoding`` and ``errors`` in binary mode."""376 if "b" in mode:377 return open(file, mode)378 5 unmodified lines384 mode: str = "r",385 encoding: t.Optional[str] = None,386 errors: t.Optional[str] = "strict",387 atomic: bool = False,388-) -> t.Tuple[t.IO, bool]:388+) -> t.Tuple[t.IO[t.Any], bool]:389 binary = "b" in mode390 391 # Standard streams first. These are simple because they ignore the392 # atomic flag. Use fsdecode to handle Path("-").62 unmodified lines455 os.chmod(tmp_filename, perm) # in case perm includes bits in umask456 457 f = _wrap_io_open(fd, mode, encoding, errors)458 af = _AtomicFile(f, tmp_filename, os.path.realpath(filename))459- return t.cast(t.IO, af), True459+ return t.cast(t.IO[t.Any], af), True460 461 462 class _AtomicFile:463- def __init__(self, f: t.IO, tmp_filename: str, real_filename: str) -> None:463+ def __init__(self, f: t.IO[t.Any], tmp_filename: str, real_filename: str) -> None:464 self._f = f465 self._tmp_filename = tmp_filename466 self._real_filename = real_filename467 self.closed = False14 unmodified lines482 483 def __enter__(self) -> "_AtomicFile":484 return self485 486- def __exit__(self, exc_type, exc_value, tb): # type: ignore486+ def __exit__(self, exc_type: t.Optional[t.Type[BaseException]], *_: t.Any) -> None:487 self.close(delete=exc_type is not None)488 489 def __repr__(self) -> str:490 return repr(self._f)2 unmodified lines493 def strip_ansi(value: str) -> str:494 return _ansi_re.sub("", value)495 496 497-def _is_jupyter_kernel_output(stream: t.IO) -> bool:497+def _is_jupyter_kernel_output(stream: t.IO[t.Any]) -> bool:498 while isinstance(stream, (_FixupStream, _NonClosingTextIOWrapper)):499 stream = stream._stream500 501 return stream.__class__.__module__.startswith("ipykernel.")502 503 504 def should_strip_ansi(505- stream: t.Optional[t.IO] = None, color: t.Optional[bool] = None505+ stream: t.Optional[t.IO[t.Any]] = None, color: t.Optional[bool] = None506 ) -> bool:507 if color is None:508 if stream is None:509 stream = sys.stdin65 unmodified lines575 def term_len(x: str) -> int:576 return len(strip_ansi(x))577 578 579-def isatty(stream: t.IO) -> bool:579+def isatty(stream: t.IO[t.Any]) -> bool:580 try:581 return stream.isatty()582 except Exception:583 return False43 unmodified linesmodified:src/click/_termui_impl.py+2 added-2 removed
91 unmodified lines92 self.current_item: t.Optional[V] = None93 self.is_hidden = not isatty(self.file)94 self._last_line: t.Optional[str] = None95 96- def __enter__(self) -> "ProgressBar":96+ def __enter__(self) -> "ProgressBar[V]":97 self.entered = True98 self.render_progress()99 return self100 101- def __exit__(self, exc_type, exc_value, tb): # type: ignore101+ def __exit__(self, *_: t.Any) -> None:102 self.render_finish()103 104 def __iter__(self) -> t.Iterator[V]:105 if not self.entered:612 unmodified linesmodified:src/click/core.py+27 added-9 removed
453 unmodified lines454 self._depth += 1455 push_context(self)456 return self457 458- def __exit__(self, exc_type, exc_value, tb): # type: ignore458+ def __exit__(self, *_: t.Any) -> None:459 self._depth -= 1460 if self._depth == 0:461 self.close()462 pop_context()242 unmodified lines705 :meta private:706 """707 return type(self)(command, info_name=command.name, parent=self)708 709+ @t.overload710 def invoke(711 __self, # noqa: B902711- __callback: t.Union["Command", t.Callable[..., t.Any]],712+ __callback: "t.Callable[..., V]",713 *args: t.Any,714 **kwargs: t.Any,715+ ) -> V:716+ ...717+718+ @t.overload719+ def invoke(720+ __self, # noqa: B902721+ __callback: "Command",722+ *args: t.Any,723+ **kwargs: t.Any,724 ) -> t.Any:725+ ...726+727+ def invoke(728+ __self, # noqa: B902729+ __callback: t.Union["Command", "t.Callable[..., V]"],730+ *args: t.Any,731+ **kwargs: t.Any,732+ ) -> t.Union[t.Any, V]:733 """Invokes a command callback in exactly the way it expects. There734 are two ways to invoke this method:735 736 1. the first argument can be a callback and all other arguments and19 unmodified lines756 raise TypeError(757 "The given command does not have a callback that can be invoked."758 )759 else:742- __callback = other_cmd.callback760+ __callback = t.cast("t.Callable[..., V]", other_cmd.callback)761 762 ctx = __self._make_sub_context(other_cmd)763 764 for param in other_cmd.params:1093 unmodified lines1858 1859 if self.command_class and kwargs.get("cls") is None:1860 kwargs["cls"] = self.command_class1861 1844- func: t.Optional[t.Callable] = None1862+ func: t.Optional[t.Callable[..., t.Any]] = None1863 1864 if args and callable(args[0]):1865 assert (1866 len(args) == 1 and not kwargs39 unmodified lines1906 Added the :attr:`group_class` attribute.1907 """1908 from .decorators import group1909 1892- func: t.Optional[t.Callable] = None1910+ func: t.Optional[t.Callable[..., t.Any]] = None1911 1912 if args and callable(args[0]):1913 assert (1914 len(args) == 1 and not kwargs362 unmodified lines2277 """2278 if value is None:2279 return () if self.multiple or self.nargs == -1 else None2280 2263- def check_iter(value: t.Any) -> t.Iterator:2281+ def check_iter(value: t.Any) -> t.Iterator[t.Any]:2282 try:2283 return _check_iter(value)2284 except TypeError:2285 # This should only happen when passing in args manually,8 unmodified lines2294 self.type, param=self, ctx=ctx2295 )2296 elif self.nargs == -1:2297 2280- def convert(value: t.Any) -> t.Tuple:2298+ def convert(value: t.Any) -> t.Tuple[t.Any, ...]:2299 return tuple(self.type(x, self, ctx) for x in check_iter(value))2300 2301 else: # nargs > 12302 2285- def convert(value: t.Any) -> t.Tuple:2303+ def convert(value: t.Any) -> t.Tuple[t.Any, ...]:2304 value = tuple(check_iter(value))2305 2306 if len(value) != self.nargs:2307 raise BadParameter(526 unmodified lines2834 # value as default.2835 if self.is_flag and not self.is_bool_flag:2836 for param in ctx.command.params:2837 if param.name == self.name and param.default:2820- return param.flag_value # type: ignore2838+ return t.cast(Option, param).flag_value2839 2840 return None2841 2842 return super().get_default(ctx, call=call)174 unmodified linesmodified:src/click/decorators.py+108 added-50 removed
11 unmodified lines12 from .core import Parameter13 from .globals import get_current_context14 from .utils import echo15 16-F = t.TypeVar("F", bound=t.Callable[..., t.Any])17-FC = t.TypeVar("FC", bound=t.Union[t.Callable[..., t.Any], Command])16+if t.TYPE_CHECKING:17+ import typing_extensions as te18 19+ P = te.ParamSpec("P")20 20-def pass_context(f: F) -> F:21+R = t.TypeVar("R")22+T = t.TypeVar("T")23+_AnyCallable = t.Callable[..., t.Any]24+_Decorator: "te.TypeAlias" = t.Callable[[T], T]25+FC = t.TypeVar("FC", bound=t.Union[_AnyCallable, Command])26+27+28+def pass_context(f: "t.Callable[te.Concatenate[Context, P], R]") -> "t.Callable[P, R]":29 """Marks a callback as wanting to receive the current context30 object as first argument.31 """32 25- def new_func(*args, **kwargs): # type: ignore33+ def new_func(*args: "P.args", **kwargs: "P.kwargs") -> "R":34 return f(get_current_context(), *args, **kwargs)35 28- return update_wrapper(t.cast(F, new_func), f)36+ return update_wrapper(new_func, f)37 38 31-def pass_obj(f: F) -> F:39+def pass_obj(f: "t.Callable[te.Concatenate[t.Any, P], R]") -> "t.Callable[P, R]":40 """Similar to :func:`pass_context`, but only pass the object on the41 context onwards (:attr:`Context.obj`). This is useful if that object42 represents the state of a nested system.43 """44 37- def new_func(*args, **kwargs): # type: ignore45+ def new_func(*args: "P.args", **kwargs: "P.kwargs") -> "R":46 return f(get_current_context().obj, *args, **kwargs)47 40- return update_wrapper(t.cast(F, new_func), f)48+ return update_wrapper(new_func, f)49 50 51 def make_pass_decorator(44- object_type: t.Type, ensure: bool = False45-) -> "t.Callable[[F], F]":52+ object_type: t.Type[T], ensure: bool = False53+) -> t.Callable[["t.Callable[te.Concatenate[T, P], R]"], "t.Callable[P, R]"]:54 """Given an object type this creates a decorator that will work55 similar to :func:`pass_obj` but instead of passing the object of the56 current context, it will find the innermost context of type57 :func:`object_type`.14 unmodified lines72 :param ensure: if set to `True`, a new object will be created and73 remembered on the context if it's not there yet.74 """75 68- def decorator(f: F) -> F:69- def new_func(*args, **kwargs): # type: ignore76+ def decorator(f: "t.Callable[te.Concatenate[T, P], R]") -> "t.Callable[P, R]":77+ def new_func(*args: "P.args", **kwargs: "P.kwargs") -> "R":78 ctx = get_current_context()79 80+ obj: t.Optional[T]81 if ensure:82 obj = ctx.ensure_object(object_type)83 else:84 obj = ctx.find_object(object_type)6 unmodified lines91 )92 93 return ctx.invoke(f, obj, *args, **kwargs)94 86- return update_wrapper(t.cast(F, new_func), f)95+ return update_wrapper(new_func, f)96 97 return decorator98 99 100 def pass_meta_key(101 key: str, *, doc_description: t.Optional[str] = None93-) -> "t.Callable[[F], F]":102+) -> "t.Callable[[t.Callable[te.Concatenate[t.Any, P], R]], t.Callable[P, R]]":103 """Create a decorator that passes a key from104 :attr:`click.Context.meta` as the first argument to the decorated105 function.106 4 unmodified lines111 112 .. versionadded:: 8.0113 """114 106- def decorator(f: F) -> F:107- def new_func(*args, **kwargs): # type: ignore115+ def decorator(f: "t.Callable[te.Concatenate[t.Any, P], R]") -> "t.Callable[P, R]":116+ def new_func(*args: "P.args", **kwargs: "P.kwargs") -> R:117 ctx = get_current_context()118 obj = ctx.meta[key]119 return ctx.invoke(f, obj, *args, **kwargs)120 112- return update_wrapper(t.cast(F, new_func), f)121+ return update_wrapper(new_func, f)122 123 if doc_description is None:124 doc_description = f"the {key!r} key from :attr:`click.Context.meta`"125 6 unmodified lines132 133 CmdType = t.TypeVar("CmdType", bound=Command)134 135 136+# variant: no call, directly as decorator for a function.137 @t.overload128-def command(129- __func: t.Callable[..., t.Any],130-) -> Command:138+def command(name: _AnyCallable) -> Command:139 ...140 141 142+# variant: with positional name and with positional or keyword cls argument:143+# @command(namearg, CommandCls, ...) or @command(namearg, cls=CommandCls, ...)144 @t.overload145 def command(136- name: t.Optional[str] = None,146+ name: t.Optional[str],147+ cls: t.Type[CmdType],148 **attrs: t.Any,138-) -> t.Callable[..., Command]:149+) -> t.Callable[[_AnyCallable], CmdType]:150 ...151 152 153+# variant: name omitted, cls _must_ be a keyword argument, @command(cmd=CommandCls, ...)154+# The correct way to spell this overload is to use keyword-only argument syntax:155+# def command(*, cls: t.Type[CmdType], **attrs: t.Any) -> ...156+# However, mypy thinks this doesn't fit the overloaded function. Pyright does157+# accept that spelling, and the following work-around makes pyright issue a158+# warning that CmdType could be left unsolved, but mypy sees it as fine. *shrug*159 @t.overload160 def command(144- name: t.Optional[str] = None,161+ name: None = None,162 cls: t.Type[CmdType] = ...,163 **attrs: t.Any,147-) -> t.Callable[..., CmdType]:164+) -> t.Callable[[_AnyCallable], CmdType]:165 ...166 167 168+# variant: with optional string name, no cls argument provided.169+@t.overload170 def command(171+ name: t.Optional[str] = ..., cls: None = None, **attrs: t.Any172+) -> t.Callable[[_AnyCallable], Command]:173+ ...174+175+176+def command(152- name: t.Union[str, t.Callable[..., t.Any], None] = None,153- cls: t.Optional[t.Type[Command]] = None,177+ name: t.Union[t.Optional[str], _AnyCallable] = None,178+ cls: t.Optional[t.Type[CmdType]] = None,179 **attrs: t.Any,155-) -> t.Union[Command, t.Callable[..., Command]]:180+) -> t.Union[Command, t.Callable[[_AnyCallable], t.Union[Command, CmdType]]]:181 r"""Creates a new :class:`Command` and uses the decorated function as182 callback. This will also automatically attach all decorated183 :func:`option`\s and :func:`argument`\s as parameters to the command.184 21 unmodified lines206 The ``params`` argument can be used. Decorated params are207 appended to the end of the list.208 """209 185- func: t.Optional[t.Callable[..., t.Any]] = None210+ func: t.Optional[t.Callable[[_AnyCallable], t.Any]] = None211 212 if callable(name):213 func = name214 name = None215 assert cls is None, "Use 'command(cls=cls)(callable)' to specify a class."216 assert not attrs, "Use 'command(**kwargs)(callable)' to provide arguments."217 218 if cls is None:194- cls = Command219+ cls = t.cast(t.Type[CmdType], Command)220 196- def decorator(f: t.Callable[..., t.Any]) -> Command:221+ def decorator(f: _AnyCallable) -> CmdType:222 if isinstance(f, Command):223 raise TypeError("Attempted to convert a callback into a command twice.")224 225 attr_params = attrs.pop("params", None)9 unmodified lines235 236 if attrs.get("help") is None:237 attrs["help"] = f.__doc__238 214- cmd = cls( # type: ignore[misc]215- name=name or f.__name__.lower().replace("_", "-"), # type: ignore[arg-type]239+ if t.TYPE_CHECKING:240+ assert cls is not None241+ assert not callable(name)242+243+ cmd = cls(244+ name=name or f.__name__.lower().replace("_", "-"),245 callback=f,246 params=params,247 **attrs,248 )5 unmodified lines254 255 return decorator256 257 258+GrpType = t.TypeVar("GrpType", bound=Group)259+260+261+# variant: no call, directly as decorator for a function.262 @t.overload263+def group(name: _AnyCallable) -> Group:264+ ...265+266+267+# variant: with positional name and with positional or keyword cls argument:268+# @group(namearg, GroupCls, ...) or @group(namearg, cls=GroupCls, ...)269+@t.overload270 def group(231- __func: t.Callable[..., t.Any],232-) -> Group:271+ name: t.Optional[str],272+ cls: t.Type[GrpType],273+ **attrs: t.Any,274+) -> t.Callable[[_AnyCallable], GrpType]:275 ...276 277 278+# variant: name omitted, cls _must_ be a keyword argument, @group(cmd=GroupCls, ...)279+# The _correct_ way to spell this overload is to use keyword-only argument syntax:280+# def group(*, cls: t.Type[GrpType], **attrs: t.Any) -> ...281+# However, mypy thinks this doesn't fit the overloaded function. Pyright does282+# accept that spelling, and the following work-around makes pyright issue a283+# warning that GrpType could be left unsolved, but mypy sees it as fine. *shrug*284 @t.overload285 def group(238- name: t.Optional[str] = None,286+ name: None = None,287+ cls: t.Type[GrpType] = ...,288 **attrs: t.Any,240-) -> t.Callable[[F], Group]:289+) -> t.Callable[[_AnyCallable], GrpType]:290 ...291 292 293+# variant: with optional string name, no cls argument provided.294+@t.overload295 def group(245- name: t.Union[str, t.Callable[..., t.Any], None] = None, **attrs: t.Any246-) -> t.Union[Group, t.Callable[[F], Group]]:296+ name: t.Optional[str] = ..., cls: None = None, **attrs: t.Any297+) -> t.Callable[[_AnyCallable], Group]:298+ ...299+300+301+def group(302+ name: t.Union[str, _AnyCallable, None] = None,303+ cls: t.Optional[t.Type[GrpType]] = None,304+ **attrs: t.Any,305+) -> t.Union[Group, t.Callable[[_AnyCallable], t.Union[Group, GrpType]]]:306 """Creates a new :class:`Group` with a function as callback. This307 works otherwise the same as :func:`command` just that the `cls`308 parameter is set to :class:`Group`.309 310 .. versionchanged:: 8.1311 This decorator can be applied without parentheses.312 """254- if attrs.get("cls") is None:255- attrs["cls"] = Group313+ if cls is None:314+ cls = t.cast(t.Type[GrpType], Group)315 316 if callable(name):258- grp: t.Callable[[F], Group] = t.cast(Group, command(**attrs))259- return grp(name)317+ return command(cls=cls, **attrs)(name)318 261- return t.cast(Group, command(name, **attrs))319+ return command(name, cls, **attrs)320 321 264-def _param_memo(f: FC, param: Parameter) -> None:322+def _param_memo(f: t.Callable[..., t.Any], param: Parameter) -> None:323 if isinstance(f, Command):324 f.params.append(param)325 else:326 if not hasattr(f, "__click_params__"):1 unmodified line328 329 f.__click_params__.append(param) # type: ignore330 331 274-def argument(*param_decls: str, **attrs: t.Any) -> t.Callable[[FC], FC]:332+def argument(*param_decls: str, **attrs: t.Any) -> _Decorator[FC]:333 """Attaches an argument to the command. All positional arguments are334 passed as parameter declarations to :class:`Argument`; all keyword335 arguments are forwarded unchanged (except ``cls``).336 This is equivalent to creating an :class:`Argument` instance manually10 unmodified lines347 348 return decorator349 350 293-def option(*param_decls: str, **attrs: t.Any) -> t.Callable[[FC], FC]:351+def option(*param_decls: str, **attrs: t.Any) -> _Decorator[FC]:352 """Attaches an option to the command. All positional arguments are353 passed as parameter declarations to :class:`Option`; all keyword354 arguments are forwarded unchanged (except ``cls``).355 This is equivalent to creating an :class:`Option` instance manually12 unmodified lines368 369 return decorator370 371 314-def confirmation_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:372+def confirmation_option(*param_decls: str, **kwargs: t.Any) -> _Decorator[FC]:373 """Add a ``--yes`` option which shows a prompt before continuing if374 not passed. If the prompt is declined, the program will exit.375 376 :param param_decls: One or more option names. Defaults to the single15 unmodified lines392 kwargs.setdefault("help", "Confirm the action without prompting.")393 return option(*param_decls, **kwargs)394 395 338-def password_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:396+def password_option(*param_decls: str, **kwargs: t.Any) -> _Decorator[FC]:397 """Add a ``--password`` option which prompts for a password, hiding398 input and asking to enter the value again for confirmation.399 400 :param param_decls: One or more option names. Defaults to the single15 unmodified lines416 package_name: t.Optional[str] = None,417 prog_name: t.Optional[str] = None,418 message: t.Optional[str] = None,419 **kwargs: t.Any,362-) -> t.Callable[[FC], FC]:420+) -> _Decorator[FC]:421 """Add a ``--version`` option which immediately prints the version422 number and exits the program.423 424 If ``version`` is not provided, Click will try to detect it using98 unmodified lines523 kwargs["callback"] = callback524 return option(*param_decls, **kwargs)525 526 469-def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:527+def help_option(*param_decls: str, **kwargs: t.Any) -> _Decorator[FC]:528 """Add a ``--help`` option which immediately prints the help page529 and exits the program.530 531 This is usually unnecessary, as the ``--help`` option is added to24 unmodified linesmodified:src/click/exceptions.py+2 added-2 removed
34 unmodified lines35 36 def __str__(self) -> str:37 return self.message38 39- def show(self, file: t.Optional[t.IO] = None) -> None:39+ def show(self, file: t.Optional[t.IO[t.Any]] = None) -> None:40 if file is None:41 file = get_text_stderr()42 43 echo(_("Error: {message}").format(message=self.format_message()), file=file)14 unmodified lines58 super().__init__(message)59 self.ctx = ctx60 self.cmd = self.ctx.command if self.ctx else None61 62- def show(self, file: t.Optional[t.IO] = None) -> None:62+ def show(self, file: t.Optional[t.IO[t.Any]] = None) -> None:63 if file is None:64 file = get_text_stderr()65 color = None66 hint = ""221 unmodified linesmodified:src/click/testing.py+6 added-6 removed
77 unmodified lines78 return self._mode79 80 81 def make_input_stream(82- input: t.Optional[t.Union[str, bytes, t.IO]], charset: str82+ input: t.Optional[t.Union[str, bytes, t.IO[t.Any]]], charset: str83 ) -> t.BinaryIO:84 # Is already an input stream.85 if hasattr(input, "read"):86- rv = _find_binary_reader(t.cast(t.IO, input))86+ rv = _find_binary_reader(t.cast(t.IO[t.Any], input))87 88 if rv is not None:89 return rv90 114 unmodified lines205 206 @contextlib.contextmanager207 def isolation(208 self,209- input: t.Optional[t.Union[str, bytes, t.IO]] = None,209+ input: t.Optional[t.Union[str, bytes, t.IO[t.Any]]] = None,210 env: t.Optional[t.Mapping[str, t.Optional[str]]] = None,211 color: bool = False,212 ) -> t.Iterator[t.Tuple[io.BytesIO, t.Optional[io.BytesIO]]]:213 """A context manager that sets up the isolation for invoking of a86 unmodified lines300 301 default_color = color302 303 def should_strip_ansi(304- stream: t.Optional[t.IO] = None, color: t.Optional[bool] = None304+ stream: t.Optional[t.IO[t.Any]] = None, color: t.Optional[bool] = None305 ) -> bool:306 if color is None:307 return not default_color308 return not color40 unmodified lines349 def invoke(350 self,351 cli: "BaseCommand",352 args: t.Optional[t.Union[str, t.Sequence[str]]] = None,353- input: t.Optional[t.Union[str, bytes, t.IO]] = None,353+ input: t.Optional[t.Union[str, bytes, t.IO[t.Any]]] = None,354 env: t.Optional[t.Mapping[str, t.Optional[str]]] = None,355 catch_exceptions: bool = True,356 color: bool = False,357 **extra: t.Any,90 unmodified lines448 )449 450 @contextlib.contextmanager451 def isolated_filesystem(452- self, temp_dir: t.Optional[t.Union[str, os.PathLike]] = None452+ self, temp_dir: t.Optional[t.Union[str, "os.PathLike[str]"]] = None453 ) -> t.Iterator[str]:454 """A context manager that creates a temporary directory and455 changes the current working directory to it. This isolates tests456 that affect the contents of the CWD to prevent them from23 unmodified linesmodified:src/click/types.py+7 added-10 removed
395 unmodified lines396 return "DateTime"397 398 399 class _NumberParamTypeBase(ParamType):400- _number_class: t.ClassVar[t.Type]400+ _number_class: t.ClassVar[t.Type[t.Any]]401 402 def convert(403 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]404 ) -> t.Any:296 unmodified lines701 702 lazy = self.resolve_lazy_flag(value)703 704 if lazy:705- f: t.IO = t.cast(706- t.IO,707- LazyFile(708- value, self.mode, self.encoding, self.errors, atomic=self.atomic705+ lf = LazyFile(706+ value, self.mode, self.encoding, self.errors, atomic=self.atomic709- ),707 )708 709 if ctx is not None:713- ctx.call_on_close(f.close_intelligently) # type: ignore710+ ctx.call_on_close(lf.close_intelligently)711 715- return f712+ return t.cast(t.IO[t.Any], lf)713 714 f, should_close = open_stream(715 value, self.mode, self.encoding, self.errors, atomic=self.atomic716 )73 unmodified lines790 writable: bool = False,791 readable: bool = True,792 resolve_path: bool = False,793 allow_dash: bool = False,797- path_type: t.Optional[t.Type] = None,794+ path_type: t.Optional[t.Type[t.Any]] = None,795 executable: bool = False,796 ):797 self.exists = exists798 self.file_okay = file_okay141 unmodified lines940 941 :param types: a list of types that should be used for the tuple items.942 """943 947- def __init__(self, types: t.Sequence[t.Union[t.Type, ParamType]]) -> None:944+ def __init__(self, types: t.Sequence[t.Union[t.Type[t.Any], ParamType]]) -> None:945 self.types = [convert_type(ty) for ty in types]946 947 def to_info_dict(self) -> t.Dict[str, t.Any]:948 info_dict = super().to_info_dict()122 unmodified linesmodified:src/click/utils.py+19 added-14 removed
19 unmodified lines20 21 if t.TYPE_CHECKING:22 import typing_extensions as te23 24-F = t.TypeVar("F", bound=t.Callable[..., t.Any])24+ P = te.ParamSpec("P")25 26+R = t.TypeVar("R")27 28+29 def _posixify(name: str) -> str:30 return "-".join(name.split()).lower()31 32 31-def safecall(func: F) -> F:33+def safecall(func: "t.Callable[P, R]") -> "t.Callable[P, t.Optional[R]]":34 """Wraps a function so that it swallows exceptions."""35 34- def wrapper(*args, **kwargs): # type: ignore36+ def wrapper(*args: "P.args", **kwargs: "P.kwargs") -> t.Optional[R]:37 try:38 return func(*args, **kwargs)39 except Exception:40 pass41+ return None42 40- return update_wrapper(t.cast(F, wrapper), func)43+ return update_wrapper(wrapper, func)44 45 46 def make_str(value: t.Any) -> str:47 """Converts a value into a valid string."""74 unmodified lines122 self.mode = mode123 self.encoding = encoding124 self.errors = errors125 self.atomic = atomic123- self._f: t.Optional[t.IO]126+ self._f: t.Optional[t.IO[t.Any]]127 128 if filename == "-":129 self._f, self.should_close = open_stream(filename, mode, encoding, errors)130 else:12 unmodified lines143 if self._f is not None:144 return repr(self._f)145 return f"<unopened file '{self.name}' {self.mode}>"146 144- def open(self) -> t.IO:147+ def open(self) -> t.IO[t.Any]:148 """Opens the file if it's not yet open. This call might fail with149 a :exc:`FileError`. Not handling this error will produce an error150 that Click shows.151 """24 unmodified lines176 177 def __enter__(self) -> "LazyFile":178 return self179 177- def __exit__(self, exc_type, exc_value, tb): # type: ignore180+ def __exit__(self, *_: t.Any) -> None:181 self.close_intelligently()182 183 def __iter__(self) -> t.Iterator[t.AnyStr]:184 self.open()185 return iter(self._f) # type: ignore186 187 188 class KeepOpenFile:186- def __init__(self, file: t.IO) -> None:189+ def __init__(self, file: t.IO[t.Any]) -> None:190 self._file = file191 192 def __getattr__(self, name: str) -> t.Any:193 return getattr(self._file, name)194 195 def __enter__(self) -> "KeepOpenFile":196 return self197 195- def __exit__(self, exc_type, exc_value, tb): # type: ignore198+ def __exit__(self, *_: t.Any) -> None:199 pass200 201 def __repr__(self) -> str:202 return repr(self._file)139 unmodified lines342 encoding: t.Optional[str] = None,343 errors: t.Optional[str] = "strict",344 lazy: bool = False,345 atomic: bool = False,343-) -> t.IO:346+) -> t.IO[t.Any]:347 """Open a file, with extra behavior to handle ``'-'`` to indicate348 a standard stream, lazy open on write, and atomic write. Similar to349 the behavior of the :class:`~click.File` param type.350 21 unmodified lines372 373 .. versionadded:: 3.0374 """375 if lazy:373- return t.cast(t.IO, LazyFile(filename, mode, encoding, errors, atomic=atomic))376+ return t.cast(377+ t.IO[t.Any], LazyFile(filename, mode, encoding, errors, atomic=atomic)378+ )379 380 f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic)381 382 if not should_close:378- f = t.cast(t.IO, KeepOpenFile(f))383+ f = t.cast(t.IO[t.Any], KeepOpenFile(f))384 385 return f386 387 388 def format_filename(384- filename: t.Union[str, bytes, os.PathLike], shorten: bool = False389+ filename: t.Union[str, bytes, "os.PathLike[t.AnyStr]"], shorten: bool = False390 ) -> str:391 """Formats a filename for user display. The main purpose of this392 function is to ensure that the filename can be displayed at all. This393 will decode the filename to unicode if necessary in a way that it will68 unmodified lines462 other cleanup code, and the case where the underlying file is not a broken463 pipe, all calls and attributes are proxied.464 """465 461- def __init__(self, wrapped: t.IO) -> None:466+ def __init__(self, wrapped: t.IO[t.Any]) -> None:467 self.wrapped = wrapped468 469 def flush(self) -> None:470 try:115 unmodified linesmodified:CHANGES.rst+3 added
3 unmodified lines4 -------------5 6 Unreleased7 8+- Improve type hinting for decorators and give all generic types parameters.9+ :issue:`2398`10 11+12 Version 8.1.313 -------------14 15 Released 2022-04-281038 unmodified linesmodified:setup.cfg+4 added
69 unmodified lines70 # bin op line break, invalid71 W50372 # zip with strict=, requires python >= 3.1073 B90574+ # string formatting opinion, B028 renamed to B90775+ B02876+ B90777 # up to 88 allowed by bugbear B95078 max-line-length = 8079 per-file-ignores =80 # __init__ exports names6 unmodified lines87 disallow_subclassing_any = True88 disallow_untyped_calls = True89 disallow_untyped_defs = True90 disallow_incomplete_defs = True91+disallow_any_generics = True92 check_untyped_defs = True93 no_implicit_optional = True94 local_partial_types = True95 no_implicit_reexport = True12 unmodified lines