Skip to content
Myr

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

10 files+197 added−112 removed

modified:src/click/_compat.py+19 added-19 removed
48 unmodified lines
49 except LookupError:50 return False515253def get_best_encoding(stream: t.IO) -> str:53def 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 lines
152 return False153 return True154155156def _is_binary_reader(stream: t.IO, default: bool = False) -> bool:156def _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.163164165def _is_binary_writer(stream: t.IO, default: bool = False) -> bool:165def _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 lines
174 return default175 return True176177178def _find_binary_reader(stream: t.IO) -> t.Optional[t.BinaryIO]:178def _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 lines
192193 return None194195196def _find_binary_writer(stream: t.IO) -> t.Optional[t.BinaryIO]:196def _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 lines
240 ) and _is_compat_stream_attr(stream, "errors", errors)241242243def _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 lines
286 )287288289def _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 lines
302 )303304305def _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 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, 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 lines
384 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 mode390391 # Standard streams first. These are simple because they ignore the392 # atomic flag. Use fsdecode to handle Path("-").
62 unmodified lines
455 os.chmod(tmp_filename, perm) # in case perm includes bits in umask456457 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), True460461462class _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 = False
14 unmodified lines
482483 def __enter__(self) -> "_AtomicFile":484 return self485486 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)488489 def __repr__(self) -> str:490 return repr(self._f)
2 unmodified lines
493def strip_ansi(value: str) -> str:494 return _ansi_re.sub("", value)495496497def _is_jupyter_kernel_output(stream: t.IO) -> bool:497def _is_jupyter_kernel_output(stream: t.IO[t.Any]) -> bool:498 while isinstance(stream, (_FixupStream, _NonClosingTextIOWrapper)):499 stream = stream._stream500501 return stream.__class__.__module__.startswith("ipykernel.")502503504def 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.stdin
65 unmodified lines
575def term_len(x: str) -> int:576 return len(strip_ansi(x))577578579def isatty(stream: t.IO) -> bool:579def isatty(stream: t.IO[t.Any]) -> bool:580 try:581 return stream.isatty()582 except Exception:583 return False
43 unmodified lines
modified:src/click/_termui_impl.py+2 added-2 removed
91 unmodified lines
92 self.current_item: t.Optional[V] = None93 self.is_hidden = not isatty(self.file)94 self._last_line: t.Optional[str] = None9596 def __enter__(self) -> "ProgressBar":96 def __enter__(self) -> "ProgressBar[V]":97 self.entered = True98 self.render_progress()99 return self100101 def __exit__(self, exc_type, exc_value, tb): # type: ignore101 def __exit__(self, *_: t.Any) -> None:102 self.render_finish()103104 def __iter__(self) -> t.Iterator[V]:105 if not self.entered:
612 unmodified lines
modified:src/click/core.py+27 added-9 removed
453 unmodified lines
454 self._depth += 1455 push_context(self)456 return self457458 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 lines
705 :meta private:706 """707 return type(self)(command, info_name=command.name, parent=self)708709 @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 ...717718 @t.overload719 def invoke(720 __self, # noqa: B902721 __callback: "Command",722 *args: t.Any,723 **kwargs: t.Any,724 ) -> t.Any:725 ...726727 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:735736 1. the first argument can be a callback and all other arguments and
19 unmodified lines
756 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)761762 ctx = __self._make_sub_context(other_cmd)763764 for param in other_cmd.params:
1093 unmodified lines
18581859 if self.command_class and kwargs.get("cls") is None:1860 kwargs["cls"] = self.command_class18611844 func: t.Optional[t.Callable] = None1862 func: t.Optional[t.Callable[..., t.Any]] = None18631864 if args and callable(args[0]):1865 assert (1866 len(args) == 1 and not kwargs
39 unmodified lines
1906 Added the :attr:`group_class` attribute.1907 """1908 from .decorators import group19091892 func: t.Optional[t.Callable] = None1910 func: t.Optional[t.Callable[..., t.Any]] = None19111912 if args and callable(args[0]):1913 assert (1914 len(args) == 1 and not kwargs
362 unmodified lines
2277 """2278 if value is None:2279 return () if self.multiple or self.nargs == -1 else None22802263 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 lines
2294 self.type, param=self, ctx=ctx2295 )2296 elif self.nargs == -1:22972280 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))23002301 else: # nargs > 123022285 def convert(value: t.Any) -> t.Tuple:2303 def convert(value: t.Any) -> t.Tuple[t.Any, ...]:2304 value = tuple(check_iter(value))23052306 if len(value) != self.nargs:2307 raise BadParameter(
526 unmodified lines
2834 # 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_value28392840 return None28412842 return super().get_default(ctx, call=call)
174 unmodified lines
modified:src/click/decorators.py+108 added-50 removed
11 unmodified lines
12from .core import Parameter13from .globals import get_current_context14from .utils import echo1516F = t.TypeVar("F", bound=t.Callable[..., t.Any])17FC = t.TypeVar("FC", bound=t.Union[t.Callable[..., t.Any], Command])16if t.TYPE_CHECKING:17 import typing_extensions as te1819 P = te.ParamSpec("P")2020def pass_context(f: F) -> F:21R = t.TypeVar("R")22T = t.TypeVar("T")23_AnyCallable = t.Callable[..., t.Any]24_Decorator: "te.TypeAlias" = t.Callable[[T], T]25FC = t.TypeVar("FC", bound=t.Union[_AnyCallable, Command])262728def 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 """3225 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)3528 return update_wrapper(t.cast(F, new_func), f)36 return update_wrapper(new_func, f)373831def pass_obj(f: F) -> F:39def 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 """4437 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)4740 return update_wrapper(t.cast(F, new_func), f)48 return update_wrapper(new_func, f)495051def 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 lines
72 :param ensure: if set to `True`, a new object will be created and73 remembered on the context if it's not there yet.74 """7568 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()7980 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 lines
91 )9293 return ctx.invoke(f, obj, *args, **kwargs)9486 return update_wrapper(t.cast(F, new_func), f)95 return update_wrapper(new_func, f)9697 return decorator9899100def 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 lines
111112 .. versionadded:: 8.0113 """114106 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)120112 return update_wrapper(t.cast(F, new_func), f)121 return update_wrapper(new_func, f)122123 if doc_description is None:124 doc_description = f"the {key!r} key from :attr:`click.Context.meta`"125
6 unmodified lines
132133CmdType = t.TypeVar("CmdType", bound=Command)134135136# variant: no call, directly as decorator for a function.137@t.overload128def command(129 __func: t.Callable[..., t.Any],130) -> Command:138def command(name: _AnyCallable) -> Command:139 ...140141142# variant: with positional name and with positional or keyword cls argument:143# @command(namearg, CommandCls, ...) or @command(namearg, cls=CommandCls, ...)144@t.overload145def 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 ...151152153# 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.overload160def 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 ...166167168# variant: with optional string name, no cls argument provided.169@t.overload170def command(171 name: t.Optional[str] = ..., cls: None = None, **attrs: t.Any172) -> t.Callable[[_AnyCallable], Command]:173 ...174175176def 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 lines
206 The ``params`` argument can be used. Decorated params are207 appended to the end of the list.208 """209185 func: t.Optional[t.Callable[..., t.Any]] = None210 func: t.Optional[t.Callable[[_AnyCallable], t.Any]] = None211212 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."217218 if cls is None:194 cls = Command219 cls = t.cast(t.Type[CmdType], Command)220196 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.")224225 attr_params = attrs.pop("params", None)
9 unmodified lines
235236 if attrs.get("help") is None:237 attrs["help"] = f.__doc__238214 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)242243 cmd = cls(244 name=name or f.__name__.lower().replace("_", "-"),245 callback=f,246 params=params,247 **attrs,248 )
5 unmodified lines
254255 return decorator256257258GrpType = t.TypeVar("GrpType", bound=Group)259260261# variant: no call, directly as decorator for a function.262@t.overload263def group(name: _AnyCallable) -> Group:264 ...265266267# variant: with positional name and with positional or keyword cls argument:268# @group(namearg, GroupCls, ...) or @group(namearg, cls=GroupCls, ...)269@t.overload270def 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 ...276277278# 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.overload285def 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 ...291292293# variant: with optional string name, no cls argument provided.294@t.overload295def 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 ...299300301def 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`.309310 .. 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)315316 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)318261 return t.cast(Group, command(name, **attrs))319 return command(name, cls, **attrs)320321264def _param_memo(f: FC, param: Parameter) -> None:322def _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 line
328329 f.__click_params__.append(param) # type: ignore330331274def argument(*param_decls: str, **attrs: t.Any) -> t.Callable[[FC], FC]:332def 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 manually
10 unmodified lines
347348 return decorator349350293def option(*param_decls: str, **attrs: t.Any) -> t.Callable[[FC], FC]:351def 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 manually
12 unmodified lines
368369 return decorator370371314def confirmation_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:372def 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.375376 :param param_decls: One or more option names. Defaults to the single
15 unmodified lines
392 kwargs.setdefault("help", "Confirm the action without prompting.")393 return option(*param_decls, **kwargs)394395338def password_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:396def 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.399400 :param param_decls: One or more option names. Defaults to the single
15 unmodified lines
416 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.423424 If ``version`` is not provided, Click will try to detect it using
98 unmodified lines
523 kwargs["callback"] = callback524 return option(*param_decls, **kwargs)525526469def help_option(*param_decls: str, **kwargs: t.Any) -> t.Callable[[FC], FC]:527def 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.530531 This is usually unnecessary, as the ``--help`` option is added to
24 unmodified lines
modified:src/click/exceptions.py+2 added-2 removed
34 unmodified lines
3536 def __str__(self) -> str:37 return self.message3839 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()4243 echo(_("Error: {message}").format(message=self.format_message()), file=file)
14 unmodified lines
58 super().__init__(message)59 self.ctx = ctx60 self.cmd = self.ctx.command if self.ctx else None6162 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 lines
modified:src/click/testing.py+6 added-6 removed
77 unmodified lines
78 return self._mode798081def 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))8788 if rv is not None:89 return rv90
114 unmodified lines
205206 @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 a
86 unmodified lines
300301 default_color = color302303 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 color
40 unmodified lines
349 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 lines
448 )449450 @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 from
23 unmodified lines
modified:src/click/types.py+7 added-10 removed
395 unmodified lines
396 return "DateTime"397398399class _NumberParamTypeBase(ParamType):400 _number_class: t.ClassVar[t.Type]400 _number_class: t.ClassVar[t.Type[t.Any]]401402 def convert(403 self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]404 ) -> t.Any:
296 unmodified lines
701702 lazy = self.resolve_lazy_flag(value)703704 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 )708709 if ctx is not None:713 ctx.call_on_close(f.close_intelligently) # type: ignore710 ctx.call_on_close(lf.close_intelligently)711715 return f712 return t.cast(t.IO[t.Any], lf)713714 f, should_close = open_stream(715 value, self.mode, self.encoding, self.errors, atomic=self.atomic716 )
73 unmodified lines
790 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_okay
141 unmodified lines
940941 :param types: a list of types that should be used for the tuple items.942 """943947 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]946947 def to_info_dict(self) -> t.Dict[str, t.Any]:948 info_dict = super().to_info_dict()
122 unmodified lines
modified:src/click/utils.py+19 added-14 removed
19 unmodified lines
2021if t.TYPE_CHECKING:22 import typing_extensions as te2324F = t.TypeVar("F", bound=t.Callable[..., t.Any])24 P = te.ParamSpec("P")2526R = t.TypeVar("R")272829def _posixify(name: str) -> str:30 return "-".join(name.split()).lower()313231def safecall(func: F) -> F:33def safecall(func: "t.Callable[P, R]") -> "t.Callable[P, t.Optional[R]]":34 """Wraps a function so that it swallows exceptions."""3534 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 None4240 return update_wrapper(t.cast(F, wrapper), func)43 return update_wrapper(wrapper, func)444546def make_str(value: t.Any) -> str:47 """Converts a value into a valid string."""
74 unmodified lines
122 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]]127128 if filename == "-":129 self._f, self.should_close = open_stream(filename, mode, encoding, errors)130 else:
12 unmodified lines
143 if self._f is not None:144 return repr(self._f)145 return f"<unopened file '{self.name}' {self.mode}>"146144 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 lines
176177 def __enter__(self) -> "LazyFile":178 return self179177 def __exit__(self, exc_type, exc_value, tb): # type: ignore180 def __exit__(self, *_: t.Any) -> None:181 self.close_intelligently()182183 def __iter__(self) -> t.Iterator[t.AnyStr]:184 self.open()185 return iter(self._f) # type: ignore186187188class KeepOpenFile:186 def __init__(self, file: t.IO) -> None:189 def __init__(self, file: t.IO[t.Any]) -> None:190 self._file = file191192 def __getattr__(self, name: str) -> t.Any:193 return getattr(self._file, name)194195 def __enter__(self) -> "KeepOpenFile":196 return self197195 def __exit__(self, exc_type, exc_value, tb): # type: ignore198 def __exit__(self, *_: t.Any) -> None:199 pass200201 def __repr__(self) -> str:202 return repr(self._file)
139 unmodified lines
342 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 lines
372373 .. 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 )379380 f, should_close = open_stream(filename, mode, encoding, errors, atomic=atomic)381382 if not should_close:378 f = t.cast(t.IO, KeepOpenFile(f))383 f = t.cast(t.IO[t.Any], KeepOpenFile(f))384385 return f386387388def 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 will
68 unmodified lines
462 other cleanup code, and the case where the underlying file is not a broken463 pipe, all calls and attributes are proxied.464 """465461 def __init__(self, wrapped: t.IO) -> None:466 def __init__(self, wrapped: t.IO[t.Any]) -> None:467 self.wrapped = wrapped468469 def flush(self) -> None:470 try:
115 unmodified lines
modified:CHANGES.rst+3 added
3 unmodified lines
4-------------56Unreleased78- Improve type hinting for decorators and give all generic types parameters.9 :issue:`2398`101112Version 8.1.313-------------1415Released 2022-04-28
1038 unmodified lines
modified:setup.cfg+4 added
69 unmodified lines
70 # 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 B95078max-line-length = 8079per-file-ignores =80 # __init__ exports names
6 unmodified lines
87disallow_subclassing_any = True88disallow_untyped_calls = True89disallow_untyped_defs = True90disallow_incomplete_defs = True91disallow_any_generics = True92check_untyped_defs = True93no_implicit_optional = True94local_partial_types = True95no_implicit_reexport = True
12 unmodified lines