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
Provenance
- Commit
a63679e- Tree
2d5b955- Author
Martijn Pieters <mj@zopatista.com>- Committer
David Lord <davidism@gmail.com>- Parent
085f414
3 files changed+135 added−56 removed
modified:src/click/core.py+20 added-2 removed
704 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:2252 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[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 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/utils.py+7 added-4 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."""538 unmodified lines