Question about decorators (with context?)

Duncan Booth duncan.booth at invalid.invalid
Sun Sep 24 08:58:31 EDT 2006


"Oliver Andrich" <oliver.andrich at gmail.com> wrote:

> I will have to wrap a lot of methods to get all the functionality I
> need. And the checking for an exception looks always the same. So I
> want to write short methods, which are decorated by my_funky_decorator
> which handles the error checking and exception handling. Sadly, this
> decorator needs access to self._wand from the current object.
> 
> So far I can only think of a solution, where I have to do something
> like that. 
> 
> @my_funky_decorator(wand=<some way to access the _wand>)
> def read_image(self, filename):
>     pass
> 
> So, I like to ask, if someone could enlighten me how to implement the
> easy decorator I mentioned in my first "example".

Just make sure your wrapper takes self as its first argument:

def my_funky_decorator(f):
   @functools.wraps(f) # Omit this if Python <2.5
   def wrapper(self, *args, **kw):
       try:
           print "wand is", self._wand
           return f(self, *args, **kw)
       except whatever:
           self.handleException()
   return wrapper

class MagickWand(object):

    def __init__(self):
        self._wand = <create a MagickWand instance using ctypes>

    @my_funky_decorator
    def read_image(self, filename):
        return <ctypes call of the MagickWand C function to read an image>



More information about the Python-list mailing list