wrapping all class methods

Robin Becker robin at jessikat.fsnet.co.uk
Fri Nov 15 13:28:46 EST 2002


..... it seems I was asking a question that Python cannot answer as traceback.print_exc()
will only print a traceback back to the point at which it's caught.
The stack frames are there and can be listed further, but I don't
think that the line number information is always good beyond the traceback.

############# traceback.py
def tracebackAdvice(origMethod, methodName):
        def wrap_traceback_method(*args, **kwargs):
                inst = args[0]
                try:
                        origMethod(*args, **kwargs)
                except:
                        print '[%s.%s]' % (inst.__class__.__name__, methodName)
                        from traceback import print_exc
                        print_exc()
                        print 'stack info'
                        import sys
                        f = sys._getframe(1)
                        while f:
                                co = f.f_code
                                print 'name:%s file:%s co_lno:%d lasti:%d f_lno:%d' % (co.co_name, co.co_filename,
co.co_firstlineno, f.f_lasti, f.f_lineno)
                                f = f.f_back

        return wrap_traceback_method

def _allMethods(C):
        from inspect import ismethod, getmembers
        M = []
        m = M.append
        for methodname,method in getmembers(C):
                if ismethod(method): m(methodname)
        return tuple(M)

def tracebackWrap(C, *M):
                for m in M or _allMethods(C):
                        setattr(C, m, tracebackAdvice(getattr(C, m), m))

if __name__=='__main__':
        class A(object):
                def f(self, x):
                        assert x>=0
                        print "real f", x
        tracebackWrap(A, "f")
        def L2():
                a = A()
                a.f(1)
                a.f(-1)
        def L1():
                L2()
        def L0():
                L1()
        L0()
#################################
C:\Python\devel\anygui\lib\anygui\backends>tbwrap.py
real f 1
[A.f]
Traceback (most recent call last):
  File "C:\Python\devel\anygui\lib\anygui\backends\tbwrap.py", line 5, in wrap_traceback_method
    origMethod(*args, **kwargs)
  File "C:\Python\devel\anygui\lib\anygui\backends\tbwrap.py", line 35, in f
    assert x>=0
AssertionError
stack info
name:L2 file:C:\Python\devel\anygui\lib\anygui\backends\tbwrap.py co_lno:38 lasti:43 f_lno:41
name:L1 file:C:\Python\devel\anygui\lib\anygui\backends\tbwrap.py co_lno:42 lasti:9 f_lno:43
name:L0 file:C:\Python\devel\anygui\lib\anygui\backends\tbwrap.py co_lno:44 lasti:9 f_lno:45
name:? file:C:\Python\devel\anygui\lib\anygui\backends\tbwrap.py co_lno:1 lasti:138 f_lno:46

C:\Python\devel\anygui\lib\anygui\backends>
-- 
Robin Becker



More information about the Python-list mailing list