Created
August 28, 2013 03:21
-
-
Save ysheng26/6361810 to your computer and use it in GitHub Desktop.
A python decorator template
This file contains hidden or 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 decorator_with_args(decorator_to_enhance): | |
""" | |
This function is supposed to be used as a decorator. | |
It must decorate an other function, that is intended to be used as a decorator. | |
Take a cup of coffee. | |
It will allow any decorator to accept an arbitrary number of arguments, | |
saving you the headache to remember how to do that every time. | |
""" | |
# We use the same trick we did to pass arguments | |
def decorator_maker(*args, **kwargs): | |
# We create on the fly a decorator that accepts only a function | |
# but keeps the passed arguments from the maker. | |
def decorator_wrapper(func): | |
# We return the result of the original decorator, which, after all, | |
# IS JUST AN ORDINARY FUNCTION (which returns a function). | |
# Only pitfall: the decorator must have this specific signature or it won't work: | |
return decorator_to_enhance(func, *args, **kwargs) | |
return decorator_wrapper | |
return decorator_maker |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment