Last Updated: February 25, 2016
·
30.92K
· papaloizouc

Python Decorators using self

I spent some time to figure out so i decide to share in case anyone is interested.
If you want to access self (instanse where decorator is called from) you can use args[0] inside the decorator.

Example:

states = {"a":"b", "b":"c", "c":"d", "d","end"}
class Foo:
     #skip some staff
    def will_change_state(f):
            def wrapper(*args):
                ret =  f(*args)
                args[0].change_state()
                return ret
            return wrapper

     def change_state(self):
            self.state = states[self.state]

     @will_change_state
     def func1(self):
           pass

     @will_change_state
     def func2(self):
           pass

2 Responses
Add your response

If you know that your decorator is always going to be called by a class method, you can also do this (and I also encourage the use of functools.wraps):

def will_change_state(f):
        @functools.wraps(f)
        def wrapper(self, *args, **kwargs):
            ret =  f(self, *args, **kwargs)
            self.change_state()
            return ret
        return wrapper

Increasing readability never hurts. (I also added **kwargs in there out of habit).

over 1 year ago ·

thank you!

over 1 year ago ·