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
Written by charalampos papaloizou
Related protips
2 Responses
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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Python
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#