Welcome, guest | Sign In | My Account | Store | Cart

Decorates a class so that it encounters a breakpoint for any call to class.method_name(self,args,*kwargs), where

  • method_name is given by string
  • only if arguments meet a test: arg_test(self,args,*kwargs) -> bool [default -> True]

Behaviour easily changed for other actions than breakpoint (logging,...)

Python, 43 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def any_args(self,*a,**k): return True

def watch_call(method_name,arg_test= any_args):
    """ Adds a Conditionnal Breakpoint to the method method_name of the decorated obj
    """
    def make_watcher(obj): 
        class _watch(obj):
            def __init__(self,*a,**k):
                init= getattr(obj,'__init__',None) 
                if init: return init(self,*a,**k)                
            def _watched_method(self,*a,**k):
                if arg_test(self,*a,**k):
                    This_is_a_breakpoint= True # Put a breakpoint here, or take any other action
                return obj.__dict__[method_name](self,*a ,**k)        
        setattr(_watch,method_name,_watch._watched_method)
        return _watch
    return make_watcher

def _________________tests__________________():pass

@watch_call("f",lambda s,*a,**k: a[0]== 1 )
class test:
    def f(self,x,y= 3):
        print "f(%s)"% (x+y)
    def g(self,x,y=3):
        print "g()"

if __name__== "__main__":
    # BreakPoint if l is appenned a list
    l=  watch_call("append",lambda s,*a,**k: isinstance(a[0],list))(list)()
    l.append('?')
    l.append([])
    print l
    # BreakPoint if d is __setattr__["a"]
    d=  watch_call("__setitem__",lambda s,*a,**k: a[0]== "a" )(dict)()
    d['a']= 1
    print d
    # Decorate class
    t= test()
    t.g(1)
    t.f(1)
    t.g(2)
    t.f(2)
Created by s_h_a_i_o on Tue, 20 Sep 2011 (MIT)
Python recipes (4591)
s_h_a_i_o's recipes (3)

Required Modules

  • (none specified)

Other Information and Tasks