Main Content

Python decorators - your own, staticmethod and classmethod

Archive - Originally posted on "The Horse's Mouth" - 2010-05-14 07:18:04 - Graham Ellis

Python Decorators are wrappers that you may apply around methods. So they're rather like the bread around a sandwich.

There are a number of standard decorators provided with Python - such as @classmethod and @staticmethod (see [here]) which allow you to turn methods into unbound (static, class) ones. You can also set up your own decorator - there's and example of that [here].

Here's how I can define my own decorator:

def summat(f):
  "Definition of your own decorator"
  def action(*args,**kwargs):
    result = f(*args,**kwargs)
    print "Err ... ",
    return result
  return action


How I wrap a method using it:

  @summat
  def getstuff(self):
    return self.stuff


And an example of how I call it:

print them.getstuff()

When should you use decorators? There are lots of potential uses - the first "classic" demonstration is for logging calls to methods, but it could also be used to provide overall / management controls on actions - such as ensuring that databases are open, or keeping tables of details of widgets in a GUI.


Illustration © - public domain image