# christian kaula

about me

Picture of Christian Kaula

Hi there, my name is Chris and I'm a student of Media Informatics. I am a lazy coder which makes me always search for tools that save time. Besides that I do all kinds of things web for money and/or fun.

contact

You can contact me via contact form if you want to get in touch with me. Further I can be found on Xing, Twitter, djangopeople.net and djangogigs.net.

Python: Decorate a Method That Gets Passed the Class Instance

Wednesday 24. March 2010

The other day I needed to decorate a method with a decorator class that knows about the owner of the method meaning the instance. This works as expected with function decorators:

def some_decorator(func):
    def decorator(self, *args, **kwargs):
        print 'instance %s of class %s is now decorated whee!' % (
            self, self.__class__
        )
        return func(*args, **kwargs)

    return decorator

class SomeClass(object):
    @some_decorator
    def dostuff(self, foo, bar):
        print 'do %s, %s' % (foo, bar)

If you need/want to use a class based decorator you have to do this:

class SomeDecorator(object):
    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        print 'instance %s of class %s this is now decorated whee!' % (
            self.obj, self.cls
        )
        return self.func.__call__(*args, **kwargs)

    def __get__(self, instance, owner):
        self.cls = owner
        self.obj = instance

        return self.__call__

class SomeClass(object):
    @SomeDecorator
    def dostuff(self, foo, bar):
        print 'do %s, %s' % (foo, bar)

Thanks to Ozgur who's post about the topic pointed me in the right direction.