09
Mar
09

decorators are pretty useful



Yesterday I wrote about a java indenter I was working on. I thought it worked just fine, but I found a source file where it didn’t perform how it should. Given that it was written in python, and there were pretty many function calls, I decided to use a decorator to do the tracing. One of the reasons I went with this decision was so I could learn more about them. After a small problem I had with the self argument not getting passed on to the function, everything went fine. The decorator first looked like this:


def trace(func):
	def ofunc(*args):
		func_name = func.__name__		
		xargs = args		
		print "entering %s with args %s" % (func_name,xargs)
		ret_val = func(*args)
		print "return value |%s|" % ret_val
		print "exiting %s\n" % (func_name)
		return ret_val
	return ofunc 

… and then it produced too much output, and the print statements were slowing the script a lot. It was to be expected, right? I guess, but still, some speed gains would be appreciated, right?

So, I’ve decided to switch the print statements inside the trace decorator with StringIO:


def trace(func):
	def ofunc(*args):
		global strio		
		func_name = func.__name__		
		xargs = args		
		print>>strio, "entering %s with args %s" % (func_name,xargs)
		ret_val = func(*args)
		print>>strio, "return value |%s|" % ret_val
		print>>strio, "exiting %s\n" % (func_name)
		return ret_val
	return ofunc 


The performance gain was noticeable indeed, but, there wasn’t a way to get the resulting string back. Enter another decorator! I decided the tracing would be over when the object would be garbage-collected, so I decorated the __del__ method with the decorator end_trace:


def end_trace(func):
	def pfunc(*args):
		global strio
		print strio.getvalue()
		strio.close()
		return func(*args)
	return pfunc	

Case solved! I think the source code indenter is working fine now, but, I’ll test it some more before I post the source code.

Advertisements

0 Responses to “decorators are pretty useful”



  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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s


Blog Stats

  • 223,857 hits

%d bloggers like this: