Question about decorators (with context?)

Oliver Andrich oliver.andrich at gmail.com
Sun Sep 24 08:35:11 EDT 2006


Hi,

sorry for the vague subject, but I can't come up with a better one so far.

I am currently writing a wrapper around ImageMagicks MagickWand
library using the ctypes module. During this development i have to
handle exceptions in an slightly different way, then python normally
handles them.

I am wrapping the libraries functionality in a class that looks like
that. (I leave out the ctypes calls and stuff as far as it is
possible.)

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>

You can see, I plan to have my own MagickWand object, which wraps the
C struct and functions. The normal habit of MagickWand is to call a
function, that returns either True or False. Based on this the user
has to check for an exception or not.

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".

Thanks and best regards,
Oliver

-- 
Oliver Andrich <oliver.andrich at gmail.com> --- http://roughbook.de/



More information about the Python-list mailing list