Python on the job - what did I miss?

This is a series of articles about features of Python and styles of programming that you wouldn't necessarily come across if you learnt Python in the course of your work. Some of the articles are about metaprogramming techniques, some are about design patterns, but all of these techniques are only available if you know that they're there.

Decorators: A neat way to modify functions

Published: 03/04/2012 by Andrew Kember (Updated on 04/04/2012) with tags: Programming.

In Python, decorators are a construction that helps reduce boilerplate code, enhance the maintainability of our code and address the separation of concerns. A decorator is a statement just above the function it decorates. Here's a simple example so you can understand what I mean:

def heading1(func):
    """Define the decorating function - this wraps the return value of the 
    string in html heading tags. Don't actually write html like this - it is a
    silly idea.

    """
    def wrapper(*args, **kwargs):
        return "<h1>" + func(*args, **kwargs) + "</h1>"
    return wrapper


# Use the decorator here, before the function definition.
@heading1
def subject():
    return "Decorators: A neat way to modify functions"
    
print subject()
# Output is "<h1>Decorators: A neat way to modify functions</h1>"

That seems very neat, but this is a simple way of writing something complicated, so there are some kinks to iron out.

Read more...