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

If you are debugging a program you may want to know if some special objects exist and where they came from.

Python, 53 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
44
45
46
47
48
49
50
51
52
53
54
import inspect
import gc

class Debug(object):

    " Subclass for collection of debugging informations "

    def __new__(cls, *a, **b):
        # Get the frame where the instantiation came from
        frame = inspect.stack()[1]
        # Continue with __new__ in super objects
        o = super(Debug, cls).__new__(cls, a, b)
        # Save important frame infos in object
        o.debug_call = list(frame[1:4]) + [frame[4][0]]
        return o

    def DebugInfo(self):
        # Split our informations
        file, line, module, source = self.debug_call
        # Format informative output
        return 'Object instantiated in file "%s", line %s, in %s: %s' % (
            file, 
            line, 
            module, 
            source.strip() )

def DumpDebugObjects(title):
    print "***", title, "***"
    gc.collect()
    for o in gc.get_objects():
        if isinstance(o, Debug):
            print o.DebugInfo()
            
if __name__=="__main__":
  
    class Test(Debug):
    
        def __init__(self, arg):
            print "Test", arg    
    
    class Test2(Test):
    
        pass
                                
    t1 = Test(1)
    t2 = Test(2)
    t3 = Test(3)

    DumpDebugObjects("We expect 3 objects")

    del t2
    
    DumpDebugObjects("Now one less")
    

At first we define the Debug class and overload the __new__ method. Then we save informations about the the penulatimate frame. The objects we want to track are subclasses of Debug, so by calling the objects DebugInfo() method we get infos about the file, line, module and an extract of the code line.

The DumpDebugObjects() function gets all objects currently alive and tests if they are an instance of the Debug class. If so it shows the debug informations.

Hope this helps by debugging long running processes.