bruno at modulix onurb at xiludom.gro
Fri May 12 10:40:51 CEST 2006

Lad wrote:
> I use Python 2.3.
> I have heard about decorators in Python 2.4.

What Python 2.4 adds is only syntactic sugar for decorators. You can do
the same - somewhat more explicitely - in 2.3.

> What is the decorator useful for?

FWIW, I'm not sure the name 'decorator' is such a great idea. A
decorator (read 'function decorator') is mainly a callable that takes a
callable as param and returns another callable, usually wrapping the
passed callable and adding some responsabilities (tracing, logging,
pre-post condition checks, etc). Two well-known examples are classmethod
and staticmethod.

The whole things looks like this:

def deco(func):
  print "decorating %s" % func.__name__
  def _wrapper(*args, **kw):
    print "%s called " % func.__name__
    res = func(*args, **kw)
    print "%s returned %s" % (func.__name__, str(res))
  return _wrapper

# python < 2.4
def somefunc():
  print "in somefunc"
  return 42

somefunc = deco(somefunc)

The syntactic sugar added in 2.4 allows you to avoid the explicit call
to deco():

# python >= 2.4
def someotherfunc():
  return "the parrot is dead"

As you see, apart from the syntactic sugar, there's nothing new here.
It's just plain old higher order function, well known in any functional

bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"

More information about the Python-list mailing list