Great Python Decorator Example


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



Copy this code and paste it in your HTML
  1. def decorator_maker_with_arguments(decorator_arg1, decorator_arg2) :
  2.  
  3. print "I make decorators ! And I accept arguments:", decorator_arg1, decorator_arg2
  4.  
  5. def my_decorator(func) :
  6. # The hability to pass arguments here is a gift from closures.
  7. # If you are not confortable with closures, you can assume it's ok,
  8. # or read : http://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python
  9. print "I am the decorator. Somehow you passed me arguments:", decorator_arg1, decorator_arg2
  10.  
  11. # Don't confuse decorator arguments and function arguments !
  12. def wrapped(function_arg1, function_arg2) :
  13. print "I am the wrapper arround the decorated function.",\
  14. "\nI can access all the variables",\
  15. "\n\t- from the decorator:", decorator_arg1, decorator_arg2,\
  16. "\n\t- from the function call:", function_arg1, function_arg2,\
  17. "\nThen I can pass them to the decorated function"
  18. return func(function_arg1, function_arg2)
  19.  
  20. return wrapped
  21.  
  22. return my_decorator
  23.  
  24. @decorator_maker_with_arguments("Leonard", "Sheldon")
  25. def decorated_function_with_arguments(function_arg1, function_arg2) :
  26. print "I am the decorated function and only knows about my arguments :",\
  27. function_arg1, function_arg2
  28.  
  29. decorated_function_with_arguments("Rajesh", "Howard")
  30. #outputs:
  31. #I make decorators ! And I accept arguments: Leonard Sheldon
  32. #I am the decorator. Somehow you passed me arguments: Leonard Sheldon
  33. #I am the wrapper arround the decorated function.
  34. #I can access all the variables
  35. # - from the decorator: Leonard Sheldon
  36. # - from the function call: Rajesh Howard
  37. #Then I can pass them to the decorated function
  38. #I am the decorated function and only knows about my arguments : Rajesh Howard

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.