Return to Snippet

Revision: 44519
at April 13, 2011 07:17 by kylewu


Initial Code
def decorator_maker_with_arguments(decorator_arg1, decorator_arg2) :

    print "I make decorators ! And I accept arguments:", decorator_arg1, decorator_arg2

    def my_decorator(func) :
        # The hability to pass arguments here is a gift from closures.
        # If you are not confortable with closures, you can assume it's ok,
        # or read : http://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python
        print "I am the decorator. Somehow you passed me arguments:", decorator_arg1, decorator_arg2

        # Don't confuse decorator arguments and function arguments !
        def wrapped(function_arg1, function_arg2) :
            print "I am the wrapper arround the decorated function.",\
                  "\nI can access all the variables",\
                  "\n\t- from the decorator:", decorator_arg1, decorator_arg2,\
                  "\n\t- from the function call:", function_arg1, function_arg2,\
                  "\nThen I can pass them to the decorated function"
            return func(function_arg1, function_arg2)

        return wrapped

    return my_decorator

@decorator_maker_with_arguments("Leonard", "Sheldon")
def decorated_function_with_arguments(function_arg1, function_arg2) :
    print "I am the decorated function and only knows about my arguments :",\
          function_arg1, function_arg2

decorated_function_with_arguments("Rajesh", "Howard")
#outputs:
#I make decorators ! And I accept arguments: Leonard Sheldon
#I am the decorator. Somehow you passed me arguments: Leonard Sheldon
#I am the wrapper arround the decorated function. 
#I can access all the variables 
#   - from the decorator: Leonard Sheldon 
#   - from the function call: Rajesh Howard 
#Then I can pass them to the decorated function
#I am the decorated function and only knows about my arguments : Rajesh Howard

Initial URL


Initial Description


Initial Title
Great Python Decorator Example

Initial Tags
python

Initial Language
Python