Python tracing decorator with optional depth argument

May 11, 2011 at 6:00 pm Leave a comment

The following code sample will print the lines in a function and the lines in the functions it calls up to a certain depth as they are executed. This is quite useful for debugging, since it prevents one from having to do ‘print bisecting’ or similar. The downside is that this can become terribly verbose, particularly if you are tracing functions with loops.

This code is untested for multiple threads

class Trace(object):
	def __init__(self, max_depth):
		self.max_depth = max_depth
		self.depth = 0

	def __call__(self, frame, reason, arg):
		if reason == 'call':
			self.depth += 1
		elif reason == 'line' and self.max_depth is not None and self.depth <= self.max_depth:
			filename = frame.f_code.co_filename
			line_no = frame.f_lineno
			line = linecache.getline(filename, line_no)
			print '%s:%s:%s' % (filename, line_no, line),
		elif reason == 'return':
			self.depth -= 1
		return self

def trace(max_depth=None):
	_trace = Trace(max_depth)
	def decorator(f):
		def _f(*args, **kwds):
			sys.settrace(_trace)
			result = f(*args, **kwds)
			sys.settrace(None)
			return result
		return _f
	return decorator
Advertisements

Entry filed under: Uncategorized.

Wifi tethering out of the box on gingerbread without root Cloning table schemas

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

Trackback this post  |  Subscribe to the comments via RSS Feed


May 2011
M T W T F S S
« Apr   Jun »
 1
2345678
9101112131415
16171819202122
23242526272829
3031  

%d bloggers like this: