09
Mar
09

cool python debugging trick



I’ve been debugging on some code, and I thought it would be great to be able to decorate functions that would perform something when called with a desired argument. I asked about in stackoverflow, and MizardX provided me with a great solution ( which I’ve hacked a bit ). Here it is :

from functools import wraps
import pdb	

def intercept(target=None,**trigger):
    def decorator(func):
        names = getattr(func,'_names',None)
        if names is None:
            code = func.func_code
            names = code.co_varnames[:code.co_argcount]
        @wraps(func)
        def decorated(*args,**kwargs):
            all_args = kwargs.copy()
            for n,v in zip(names,args):
                all_args[n] = v
            for k,v in trigger.iteritems():
                if k in all_args and all_args[k] == v:
					if not target is None:                    
						return target(all_args)
					else:
						pdb.set_trace()
            return func(*args,**kwargs)
        decorated._names = names
        return decorated
    return decorator

Assuming we have the following function:

def whatever(a,b):
	# do something with a and b

We can do some cool hacking on it :

  • by decorating it like this : @intercept(a=20), the python debugger will kick in and stop the function’s execution if a was passed the value 20
  • by decorating it like this : @intercept(function_here,@a=20), the function will be called and the debugger won’t fire up

Cool, right?

Advertisements

0 Responses to “cool python debugging trick”



  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

  • 221,316 hits

%d bloggers like this: