Skip to content
Myr

Type hinting: improve decorator annotations

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

A combination of overloads, TypeVar, ParamSpec and Concatenate make it possible to tell the type checker more about what kinds of callables are expected and what is being returned.

authored by Martijn Pieters · committed by David Lord · parent 085f414 · Browse files · 3 files+135 added−56 removed
This commit

State

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

Diff stats

3 files+135 added−56 removed

  • other:+135 added−56 removed

3 files+135 added−56 removed

modified:src/click/core.py+20 added-2 removed
704 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:
2252 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[t.Any], 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/utils.py+7 added-4 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."""
538 unmodified lines