Created
September 1, 2016 16:07
-
-
Save Steven-Wilson/13b93b7a6c35ba4056ad5b8e8d20cc81 to your computer and use it in GitHub Desktop.
Simplifies creation of decorators that have arguments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def args_deco(deco): | |
''' Simplifies creation of decorators that have arguments. | |
Example Usage: | |
from functools import wraps | |
@args_deco | |
def logged(fn, enabled=False, label="NOTE: "): | |
if enabled: | |
@wraps(fn) | |
def inner(*args, **kwargs): | |
print(label + fn.__qualname__) | |
return fn(*args, **kwargs) | |
return inner | |
else: | |
return fn | |
@logged(enabled=True) | |
def add(a, b, c=5): | |
'Adds 3 numbers' | |
return a + b + c | |
add(1, 2) # NOTE: add | |
help(add) # Help on function add in module __main__: | |
# | |
# add(a, b, c=5) | |
# Adds 3 numbers | |
''' | |
def argument_accepter(*args, **kwargs): | |
def new_decorator(fn): | |
return deco(fn, *args, **kwargs) | |
return new_decorator | |
return argument_accepter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment