Archive for the 'decorator' Category


a decorator that could come in handy

def hook(func):
	def mcall(self,*arg,**karg):
		func_name 	= func.__name__
		before_func	= getattr(self,"before_%s" % func_name,None)
		after_func  = getattr(self,"after_%s" % func_name,None)
		if before_func:
		res = func(self,*arg,**karg)
		if after_func:
		return res
	return mcall

class TestClass:
	def xec_me(self):
		print "xec_me called"
		return 50
	def before_xec_me(self):
		print "before xec_me"
	def after_xec_me(self):
		print "after xec_me"

x = TestClass()
res = x.xec_me()
print res

Given a class, if the @hook decorator ( maybe not the best name ) is applied, before that method gets executed, it will search for a method called before_ and the name of the method. If that method is found, it will be executed. Same thing applies to after, just that it will be executed after the execution of the decorated method.

Here’s the output this will produce:

before xec_me
xec_me called
after xec_me

Blog Stats

  • 259,585 hits