Skip to content

Instantly share code, notes, and snippets.

@lqc
Created December 20, 2010 22:43
Show Gist options
  • Save lqc/749149 to your computer and use it in GitHub Desktop.
Save lqc/749149 to your computer and use it in GitHub Desktop.
Decorator to create well-behaving decorators :)
def decorator_with_kwargs(decorator):
"""
There are many techniques to produce decorators that can be used with
arguments and without them. Accepting only keyword arguments is the simples, IMHO.
>>> def execution_decorator(view, opts):
... return view(**opts)
...
>>> def format_kwargs(**kwargs):
... return "ARGS: %r" % kwargs
...
>>> decorator_with_kwargs(execution_decorator)(format_kwargs)
"ARGS: {}"
>>> decorator_with_kwargs(execution_decorator)()(format_kwargs)
"ARGS: {}"
>>> decorator_with_kwargs(execution_decorator)(a=True, b='')(format_kwargs)
"ARGS: {'a': True, 'b': ''}"
"""
@functools.wraps(decorator)
def kwargs_decorator(*args, **kwargs):
if len(args) > 1:
raise ValueError("This decorator accepts only keyword arguments.")
if len(args) == 1: # No arguments
if not isinstance(args[0], collections.Callable):
raise ValueError("This decorator accepts only keyword arguments.")
return decorator(args[0], {})
return functools.wraps(decorator)(lambda v: decorator(v, kwargs))
return kwargs_decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment