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

0 Responses to “a decorator that could come in handy”

  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog Stats

  • 265,754 hits

%d bloggers like this: