Writing Python Function Decorators

Python has a pretty neat way, of letting you write function decorators.

A Function decorator in general, alters or appends to the functionality performed by the decorated method, without having to directly depend on or know it.

Thus it is possible, to use decorators to declare aspects, without re-writing the same code over and over again.

In python, you can decorate a function by using the following syntax:

@my_decorator(argument='value')
def my_function(arg1, arg2):
    print "Something with %s and %s" % (arg1, arg2)

By doing that, python exchanges any calls to your method, by calls to the decorator, defined as my_decorator. This decorator can now decide, to do some additional work and (if wanted) call the original function.

To define a decorator, you have to write a function factory. That is a function, that defines and returns another function, that can be called with the original function as an argument.

def my_decorator(argument):
    def outer_wrapper(original_method):
        # This code gets called, when the decorated
        # function gets defined

        def inner_wrapper(*args, **kwargs):
            # This method gets called, instead of the
            # actual function call to the decorated
            # function.
            print "I come from before the function"
            return_value = original_method(args, kwargs)
            print "The method returned %s" % return_value
            return return_value

        return inner_wrapper
    return outer_wrapper

Have fun.