Merge pull request #1807 from pallets/pass-meta
Before adoption: this commit came in with the history the project adopted, so no landing records it.
add pass_meta_key decorator
authored by David Lord · committed by GitHub · parents 1cb8609, d2b315a · Browse files · 5 files·+79 added−7 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+79 added−7 removed
- tests:+23 added−0 removed
- other:+56 added−7 removed
Provenance
- Commit
a6fea31- Tree
4417c81- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
1cb8609- Parent 2
d2b315a
5 files changed+79 added−7 removed
modified:docs/api.rst+3 added
29 unmodified lines30 .. autofunction:: pass_obj31 32 .. autofunction:: make_pass_decorator33 34+.. autofunction:: click.decorators.pass_meta_key35+36+37 Utilities38 ---------39 40 .. autofunction:: echo169 unmodified linesmodified:docs/conf.py+1 added
22 unmodified lines23 "pallets_sphinx_themes",24 "sphinx_issues",25 "sphinx_tabs.tabs",26 ]27+autodoc_typehints = "description"28 intersphinx_mapping = {"python": ("https://docs.python.org/3/", None)}29 issues_github_path = "pallets/click"30 31 # HTML -----------------------------------------------------------------28 unmodified linesmodified:src/click/decorators.py+49 added-7 removed
1 import inspect2+import typing as t3 from functools import update_wrapper4 5 from .core import Argument6 from .core import Command1 unmodified line8 from .core import Option9 from .globals import get_current_context10 from .utils import echo11 12+if t.TYPE_CHECKING:13+ F = t.TypeVar("F", bound=t.Callable[..., t.Any])14 15+12-def pass_context(f):16+def pass_context(f: "F") -> "F":17 """Marks a callback as wanting to receive the current context18 object as first argument.19 """20 21 def new_func(*args, **kwargs):22 return f(get_current_context(), *args, **kwargs)23 20- return update_wrapper(new_func, f)24+ return update_wrapper(t.cast("F", new_func), f)25 26 23-def pass_obj(f):27+def pass_obj(f: "F") -> "F":28 """Similar to :func:`pass_context`, but only pass the object on the29 context onwards (:attr:`Context.obj`). This is useful if that object30 represents the state of a nested system.31 """32 33 def new_func(*args, **kwargs):34 return f(get_current_context().obj, *args, **kwargs)35 32- return update_wrapper(new_func, f)36+ return update_wrapper(t.cast("F", new_func), f)37 38 35-def make_pass_decorator(object_type, ensure=False):39+def make_pass_decorator(40+ object_type: t.Type, ensure: bool = False41+) -> "t.Callable[[F], F]":42 """Given an object type this creates a decorator that will work43 similar to :func:`pass_obj` but instead of passing the object of the44 current context, it will find the innermost context of type45 :func:`object_type`.14 unmodified lines60 :param ensure: if set to `True`, a new object will be created and61 remembered on the context if it's not there yet.62 """63 58- def decorator(f):64+ def decorator(f: "F") -> "F":65 def new_func(*args, **kwargs):66 ctx = get_current_context()67+68 if ensure:69 obj = ctx.ensure_object(object_type)70 else:71 obj = ctx.find_object(object_type)72+73 if obj is None:74 raise RuntimeError(75 "Managed to invoke callback without a context"76 f" object of type {object_type.__name__!r}"77 " existing."78 )79+80 return ctx.invoke(f, obj, *args, **kwargs)81 73- return update_wrapper(new_func, f)82+ return update_wrapper(t.cast("F", new_func), f)83 84 return decorator85 86 87+def pass_meta_key(88+ key: str, *, doc_description: t.Optional[str] = None89+) -> "t.Callable[[F], F]":90+ """Create a decorator that passes a key from91+ :attr:`click.Context.meta` as the first argument to the decorated92+ function.93+94+ :param key: Key in ``Context.meta`` to pass.95+ :param doc_description: Description of the object being passed,96+ inserted into the decorator's docstring. Defaults to "the 'key'97+ key from Context.meta".98+99+ .. versionadded:: 8.0100+ """101+102+ def decorator(f: "F") -> "F":103+ def new_func(*args, **kwargs):104+ ctx = get_current_context()105+ obj = ctx.meta[key]106+ return ctx.invoke(f, obj, *args, **kwargs)107+108+ return update_wrapper(t.cast("F", new_func), f)109+110+ if doc_description is None:111+ doc_description = f"the {key!r} key from :attr:`click.Context.meta`"112+113+ decorator.__doc__ = (114+ f"Decorator that passes {doc_description} as the first argument"115+ " to the decorated function."116+ )117+ return decorator118+119+120 def _make_command(f, name, attrs, cls):121 if isinstance(f, Command):122 raise TypeError("Attempted to convert a callback into a command twice.")123 try:294 unmodified linesmodified:tests/test_context.py+23 added
2 unmodified lines3 import pytest4 5 import click6 from click.core import ParameterSource7+from click.decorators import pass_meta_key8 9 10 def test_ensure_context_objects(runner):11 class Foo:139 unmodified lines151 152 runner.invoke(cli, [], catch_exceptions=False)153 154 155+def test_make_pass_meta_decorator(runner):156+ @click.group()157+ @click.pass_context158+ def cli(ctx):159+ ctx.meta["value"] = "good"160+161+ @cli.command()162+ @pass_meta_key("value")163+ def show(value):164+ return value165+166+ result = runner.invoke(cli, ["show"], standalone_mode=False)167+ assert result.return_value == "good"168+169+170+def test_make_pass_meta_decorator_doc():171+ pass_value = pass_meta_key("value")172+ assert "the 'value' key from :attr:`click.Context.meta`" in pass_value.__doc__173+ pass_value = pass_meta_key("value", doc_description="the test value")174+ assert "passes the test value" in pass_value.__doc__175+176+177 def test_context_pushing():178 rv = []179 180 @click.command()187 unmodified linesmodified:CHANGES.rst+3 added
182 unmodified lines183 - The ``Path`` param type can be passed ``path_type=pathlib.Path`` to184 return a path object instead of a string. :issue:`405`185 - ``TypeError`` is raised when parameter with ``multiple=True`` or186 ``nargs > 1`` has non-iterable default. :issue:`1749`187+- Add a ``pass_meta_key`` decorator for passing a key from188+ ``Context.meta``. This is useful for extensions using ``meta`` to189+ store information. :issue:`1739`190 191 192 Version 7.1.2193 -------------635 unmodified lines