Decorators can be thought of as functions which take a function as a parameter, and return a new function which wraps the passed in function with some new functionality.
def decorate(func):
def wrapped():
print 'before'
func()
print 'after'
return wrapped
Let's say we have a function foo() which we want to decorate; we use the following syntax:
@decorate
def foo():
print 'foo'
Now, calling foo() results in the following:
before
foo
after
Here is a base class which can be extended to add custom before and after functionality
class decorate:
"""
A decorator which can be extended to allow custom before and after
functionality to be called around a function
"""
def before(self):
pass
def after(self):
pass
def __call__(self,func):
def new_f(*args,**kw):
self.before()
try:
res = func(*args,**kw)
self.after()
return res
except:
self.after()
raise
return new_f
Extend this class and override before and after:
class print_before_after(decorate):
def before(self):
print 'before'
def after(self):
print 'after'
@print_before_after() # note here we can pass args
def foo():
print 'foo'
No comments:
Post a Comment