Python Decorators: What they are underneath

Sean Gillies just wrote a great post on the use of Python decorators to help you write prettier code. he didn’t quite go into what decorators are underneath though, which is something I think that it’s important to realize to understand how decorators work.

Decorators are just function wrappers around your functions. In all the languages I use on a regular basis, functions are just another variable: they can be passed around in the same way objects can. The pretty syntax for decorators is just a way to say “Pass this function into the function I’ve just defined, and return me a new function, called the same thing as my old one was.”

If you are happy with only supporting Python2.4 and above, that’s a great way to work. Sadly, not all of us are: for example, the current release of Jython is still at 2.2. ;) More seriously, people who are maintaining older systems may not have newer Python functions available yet.

That doesn’t mean you can’t get the benefit of decorators — at least, I’ve never found it to mean that. Instead, it just means your code is a bit less ‘pretty’ to look at. Instead of functions being ‘deocrated’:

@logprints
def work():
    print "Starting some work."
    print "Doing some work ..."
    print "Finished the work ..."

You can simply wrap your function in the decorator:

def work():
    print "Starting some work."
    print "Doing some work ..."
    print "Finished the work ..."
work = logprints(work)

The idea of passing functions around is one of the things that took me a while to get used to, but learning it has helped me with a lot of code since then.

TileCache and FeatureServer don’t use decorators, specifically because they seek to support older Python versions. If you’re writing code that’s only forward looking, using all the advanced features of Python may fit your bill. But when you find yourself on an old machine some day, where all you have is Python 2.2, sometimes it’s nice to know a little bit about what’s going on underneath.

3 Responses to “Python Decorators: What they are underneath”

  1. Sean Gillies Says:

    Glad you liked it. You’re right, decoration is largely syntatic sugar, but it standardizes the technique, promotes DRY, and makes the wrapping very obvious to a programmers eye. My eye, at least.

    I disagree that use of decorators means that my code is “only forward looking”.
    Decorators appeared in Python 2.4, in 2004. 4 years of backwards compatibility is pretty good, I say.

  2. Jeremy Dunck Says:

    FWIW, Jython 2.5b0 was released in October.

  3. crschmidt Says:

    Jeremy:

    Perhaps I don’t understand Jython version numbering, but generally I assume ‘bX’ to be indicitive of a beta release. In fact, the Jython project still says “For production use please continue to use Jython 2.2.1.” So, it seems to me that Jython is still at 2.2 for anyone who wants to work in production.

Leave a Reply