Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@pirate
Last active September 20, 2017 20:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pirate/5720dcf862397ce335978c69ebb36820 to your computer and use it in GitHub Desktop.
Save pirate/5720dcf862397ce335978c69ebb36820 to your computer and use it in GitHub Desktop.
def optional_arg_decorator(fn):
"""
wrap a decorator so that it can optionally take args/kwargs
when decorating a func
"""
# http://stackoverflow.com/a/32292739/2156113
@wraps(fn)
def wrapped_decorator(*args, **kwargs):
is_bound_method = args and hasattr(args[0], fn.__name__)
if is_bound_method:
klass, args = args[0], args[1:]
# If no arguments were passed...
if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
if is_bound_method:
return fn(klass, args[0])
else:
return fn(args[0])
else:
def real_decorator(decoratee):
if is_bound_method:
return fn(klass, decoratee, *args, **kwargs)
else:
return fn(decoratee, *args, **kwargs)
return real_decorator
return wrapped_decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment