decorator accepts any argument


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. def decorator_with_args(decorator_to_enhance) :
  2. """
  3. This function is supposed to be used as a decorator.
  4. It must decorate an other function, that is intended to be used as a decorator.
  5. Take a cup of coffee.
  6. It will allow any decorator to accept an arbitrary number of arguments,
  7. saving you the headache to remember how to do that every time.
  8. """
  9.  
  10. # We use the same trick we did to pass arguments
  11. def decorator_maker(*args, **kwargs) :
  12.  
  13. # We create on the fly a decorator that accepts only a function
  14. # but keeps the passed arguments from the maker .
  15. def decorator_wrapper(func) :
  16.  
  17. # We return the result of the original decorator, which, after all,
  18. # IS JUST AN ORDINARY FUNCTION (which returns a function).
  19. # Only pitfall : the decorator must have this specific signature or it won't work :
  20. return decorator_to_enhance(func, *args, **kwargs)
  21.  
  22. return decorator_wrapper
  23.  
  24. return decorator_maker

URL: http://stackoverflow.com/questions/739654/understanding-python-decorators

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.