Advertisement
lessientelrunya

Decorators with kwargs

Apr 6th, 2017
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.96 KB | None | 0 0
  1. def decorator_maker_with_arguments(decorator_arg1, decorator_arg2):
  2.  
  3.     print("I make decorators! And I accept arguments: {0}, {1}".format(decorator_arg1, decorator_arg2))
  4.  
  5.     def my_decorator(func):
  6.         # The ability to pass arguments here is a gift from closures.
  7.         # If you are not comfortable 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: {0}, {1}".format(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 around the decorated function.\n"
  14.                   "I can access all the variables\n"
  15.                   "\t- from the decorator: {0} {1}\n"
  16.                   "\t- from the function call: {2} {3}\n"
  17.                   "Then I can pass them to the decorated function"
  18.                   .format(decorator_arg1, decorator_arg2,
  19.                           function_arg1, function_arg2))
  20.             return func(function_arg1, function_arg2)
  21.  
  22.         return wrapped
  23.  
  24.     return my_decorator
  25.  
  26. @decorator_maker_with_arguments("Felicity", "Raven")
  27. def decorated_function_with_arguments(function_arg1, function_arg2):
  28.     print("I am the decorated function and only knows about my arguments: {0}"
  29.            " {1}".format(function_arg1, function_arg2))
  30.  
  31. decorated_function_with_arguments("Hermione", "Blair")
  32. #outputs:
  33. #I make decorators! And I accept arguments: Felicity Raven
  34. #I am the decorator. Somehow you passed me arguments: Felicity Raven
  35. #I am the wrapper around the decorated function.
  36. #I can access all the variables
  37. #   - from the decorator: Felicity Raven
  38. #   - from the function call: Hermione Blair
  39. #Then I can pass them to the decorated function
  40. #I am the decorated function and only knows about my arguments: Hermione Blair
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement