diff options
author | David Lord <davidism@gmail.com> | 2021-03-05 08:47:37 -0800 |
---|---|---|
committer | David Lord <davidism@gmail.com> | 2021-03-05 08:47:37 -0800 |
commit | d2b315ae317d96860323fbed67c3736df7928ece (patch) | |
tree | 4417c81abb365bef5d495ccc8a86c20b85de3383 /src/click/decorators.py | |
parent | 21a68bd1776248ff071bbfc321d81e9f341b5250 (diff) | |
download | click-d2b315ae317d96860323fbed67c3736df7928ece.tar.gz |
typing for pass decorators
Diffstat (limited to 'src/click/decorators.py')
-rw-r--r-- | src/click/decorators.py | 20 |
1 files changed, 13 insertions, 7 deletions
diff --git a/src/click/decorators.py b/src/click/decorators.py index d2fe105..43c8fa2 100644 --- a/src/click/decorators.py +++ b/src/click/decorators.py @@ -12,7 +12,8 @@ from .utils import echo if t.TYPE_CHECKING: F = t.TypeVar("F", bound=t.Callable[..., t.Any]) -def pass_context(f): + +def pass_context(f: "F") -> "F": """Marks a callback as wanting to receive the current context object as first argument. """ @@ -20,10 +21,10 @@ def pass_context(f): def new_func(*args, **kwargs): return f(get_current_context(), *args, **kwargs) - return update_wrapper(new_func, f) + return update_wrapper(t.cast("F", new_func), f) -def pass_obj(f): +def pass_obj(f: "F") -> "F": """Similar to :func:`pass_context`, but only pass the object on the context onwards (:attr:`Context.obj`). This is useful if that object represents the state of a nested system. @@ -32,10 +33,12 @@ def pass_obj(f): def new_func(*args, **kwargs): return f(get_current_context().obj, *args, **kwargs) - return update_wrapper(new_func, f) + return update_wrapper(t.cast("F", new_func), f) -def make_pass_decorator(object_type, ensure=False): +def make_pass_decorator( + object_type: t.Type, ensure: bool = False +) -> "t.Callable[[F], F]": """Given an object type this creates a decorator that will work similar to :func:`pass_obj` but instead of passing the object of the current context, it will find the innermost context of type @@ -58,22 +61,25 @@ def make_pass_decorator(object_type, ensure=False): remembered on the context if it's not there yet. """ - def decorator(f): + def decorator(f: "F") -> "F": def new_func(*args, **kwargs): ctx = get_current_context() + if ensure: obj = ctx.ensure_object(object_type) else: obj = ctx.find_object(object_type) + if obj is None: raise RuntimeError( "Managed to invoke callback without a context" f" object of type {object_type.__name__!r}" " existing." ) + return ctx.invoke(f, obj, *args, **kwargs) - return update_wrapper(new_func, f) + return update_wrapper(t.cast("F", new_func), f) return decorator |