wrapping all class methods

Robin Becker robin at jessikat.fsnet.co.uk
Fri Nov 15 06:53:59 EST 2002


In a partially successful attempt at wrapping all methods in a module I used the
appended code. It does add a traceback wrapper to each method,
but the tracebacks don't continue back very far ie I typically see something like

[Application.__getattr__]
Traceback (most recent call last):
  File "<string>", line 3, in __getattr__
  File "C:\Python\devel\anygui\lib\anygui\Attribs.py", line 67, in __getattr__
    raise AttributeError, name
AttributeError: wrapper


ie the traceback seems to get stuck in the wrapper method. What's
the 'proper' pythonic way to do this kind of global wrapping?

##### attempt at wrapping all methods
n = 0
from inspect import isclass, ismethod, getmembers
def makeTBWrap(C,methodname):
        import new
        global n
        oldmethodname = '_%d_tbWrap_%s' % (n,methodname)
        oldmethod = getattr(C,methodname)
        S = []
        s = S.append
        s('def %s(self,*A,**K):' % methodname)
        s('\ttry:')
        s('\t\treturn self.%s(*A,**K)' % oldmethodname)
        s('\texcept:')
        s('\t\timport traceback')
        s('\t\tprint \'[%s.%s]\'' % (C.__name__,methodname))
        s('\t\ttraceback.print_exc()')
        s('\t\traise')
        s('setattr(C,oldmethodname,oldmethod)')
        s('setattr(C,methodname,new.instancemethod(%s,None,C))' % methodname)
        exec '\n'.join(S) + '\n' in locals()
        n += 1

for a in __all__:
        C = globals()[a]
        if isclass(C):
                M = []
                m = M.append
                for methodname,method in getmembers(C):
                        if ismethod(method): m(methodname)
                for methodname in M: makeTBWrap(C,methodname)
-- 
Robin Becker



More information about the Python-list mailing list