diff options
author | David Lord <davidism@gmail.com> | 2021-03-05 08:46:06 -0800 |
---|---|---|
committer | David Lord <davidism@gmail.com> | 2021-03-05 08:46:06 -0800 |
commit | 21a68bd1776248ff071bbfc321d81e9f341b5250 (patch) | |
tree | a00988960c657a8367d0bec4766c9f3644ec0957 /src/click/decorators.py | |
parent | 1cb86096124299579156f2c983efe05585f1a01b (diff) | |
download | click-21a68bd1776248ff071bbfc321d81e9f341b5250.tar.gz |
add pass_meta_key decorator
Diffstat (limited to 'src/click/decorators.py')
-rw-r--r-- | src/click/decorators.py | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/src/click/decorators.py b/src/click/decorators.py index 5742f05..d2fe105 100644 --- a/src/click/decorators.py +++ b/src/click/decorators.py @@ -1,4 +1,5 @@ import inspect +import typing as t from functools import update_wrapper from .core import Argument @@ -8,6 +9,8 @@ from .core import Option from .globals import get_current_context from .utils import echo +if t.TYPE_CHECKING: + F = t.TypeVar("F", bound=t.Callable[..., t.Any]) def pass_context(f): """Marks a callback as wanting to receive the current context @@ -75,6 +78,39 @@ def make_pass_decorator(object_type, ensure=False): return decorator +def pass_meta_key( + key: str, *, doc_description: t.Optional[str] = None +) -> "t.Callable[[F], F]": + """Create a decorator that passes a key from + :attr:`click.Context.meta` as the first argument to the decorated + function. + + :param key: Key in ``Context.meta`` to pass. + :param doc_description: Description of the object being passed, + inserted into the decorator's docstring. Defaults to "the 'key' + key from Context.meta". + + .. versionadded:: 8.0 + """ + + def decorator(f: "F") -> "F": + def new_func(*args, **kwargs): + ctx = get_current_context() + obj = ctx.meta[key] + return ctx.invoke(f, obj, *args, **kwargs) + + return update_wrapper(t.cast("F", new_func), f) + + if doc_description is None: + doc_description = f"the {key!r} key from :attr:`click.Context.meta`" + + decorator.__doc__ = ( + f"Decorator that passes {doc_description} as the first argument" + " to the decorated function." + ) + return decorator + + def _make_command(f, name, attrs, cls): if isinstance(f, Command): raise TypeError("Attempted to convert a callback into a command twice.") |