How to decorate a method inside a class?

gath picture gath · Sep 2, 2009 · Viewed 35k times · Source

I am attempting to decorate a method inside a class but python is throwing an error. My class looks like this:

from pageutils import formatHeader

class myPage(object):
   def __init__(self):
      self.PageName = ''

   def createPage(self):
      pageHeader = self.createHeader()

   @formatHeader   #<----- decorator
   def createHeader(self):
       return "Page Header ",self.PageName

if __name__=="__main__":
   page = myPage()
   page.PageName = 'My Page'
   page.createPage()

pageutils.py:

def formatHeader(fn):
   def wrapped():
       return '<div class="page_header">'+fn()+'</div>'
   return wrapped

Python throws the following error

self.createHeader()
TypeError: wrapped() takes no arguments (1 given)

Where am I goofing?

Answer

krawyoti picture krawyoti · Sep 2, 2009

You are omitting the self parameter which is present in the undecorated function (createHeader in your case).

def formatHeader(fn):
    from functools import wraps
    @wraps(fn)
    def wrapper(self):
        return '<div class="page_header">'+fn(self)+'</div>'
    return wrapper

If you are unsure about the signature of the function you want to decorate, you can make it rather general as follows:

def formatHeader(fn):
    from functools import wraps
    @wraps(fn)
    def wrapper(*args, **kw):
        return '<div class="page_header">'+fn(*args, **kw)+'</div>'
    return wrapper