Skip to content
Myr

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

5 files+79 added−7 removed

modified:docs/api.rst+3 added
29 unmodified lines
30.. autofunction:: pass_obj3132.. autofunction:: make_pass_decorator3334.. autofunction:: click.decorators.pass_meta_key353637Utilities38---------3940.. autofunction:: echo
169 unmodified lines
modified:docs/conf.py+1 added
22 unmodified lines
23 "pallets_sphinx_themes",24 "sphinx_issues",25 "sphinx_tabs.tabs",26]27autodoc_typehints = "description"28intersphinx_mapping = {"python": ("https://docs.python.org/3/", None)}29issues_github_path = "pallets/click"3031# HTML -----------------------------------------------------------------
28 unmodified lines
modified:src/click/decorators.py+49 added-7 removed
1import inspect2import typing as t3from functools import update_wrapper45from .core import Argument6from .core import Command
1 unmodified line
8from .core import Option9from .globals import get_current_context10from .utils import echo1112if t.TYPE_CHECKING:13 F = t.TypeVar("F", bound=t.Callable[..., t.Any])141512def pass_context(f):16def pass_context(f: "F") -> "F":17 """Marks a callback as wanting to receive the current context18 object as first argument.19 """2021 def new_func(*args, **kwargs):22 return f(get_current_context(), *args, **kwargs)2320 return update_wrapper(new_func, f)24 return update_wrapper(t.cast("F", new_func), f)252623def pass_obj(f):27def 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 """3233 def new_func(*args, **kwargs):34 return f(get_current_context().obj, *args, **kwargs)3532 return update_wrapper(new_func, f)36 return update_wrapper(t.cast("F", new_func), f)373835def make_pass_decorator(object_type, ensure=False):39def 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 lines
60 :param ensure: if set to `True`, a new object will be created and61 remembered on the context if it's not there yet.62 """6358 def decorator(f):64 def decorator(f: "F") -> "F":65 def new_func(*args, **kwargs):66 ctx = get_current_context()6768 if ensure:69 obj = ctx.ensure_object(object_type)70 else:71 obj = ctx.find_object(object_type)7273 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 )7980 return ctx.invoke(f, obj, *args, **kwargs)8173 return update_wrapper(new_func, f)82 return update_wrapper(t.cast("F", new_func), f)8384 return decorator858687def 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.9394 :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".9899 .. versionadded:: 8.0100 """101102 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)107108 return update_wrapper(t.cast("F", new_func), f)109110 if doc_description is None:111 doc_description = f"the {key!r} key from :attr:`click.Context.meta`"112113 decorator.__doc__ = (114 f"Decorator that passes {doc_description} as the first argument"115 " to the decorated function."116 )117 return decorator118119120def _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 lines
modified:tests/test_context.py+23 added
2 unmodified lines
3import pytest45import click6from click.core import ParameterSource7from click.decorators import pass_meta_key8910def test_ensure_context_objects(runner):11 class Foo:
139 unmodified lines
151152 runner.invoke(cli, [], catch_exceptions=False)153154155def test_make_pass_meta_decorator(runner):156 @click.group()157 @click.pass_context158 def cli(ctx):159 ctx.meta["value"] = "good"160161 @cli.command()162 @pass_meta_key("value")163 def show(value):164 return value165166 result = runner.invoke(cli, ["show"], standalone_mode=False)167 assert result.return_value == "good"168169170def 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__175176177def test_context_pushing():178 rv = []179180 @click.command()
187 unmodified lines
modified:CHANGES.rst+3 added
182 unmodified lines
183- 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`190191192Version 7.1.2193-------------
635 unmodified lines