how to replace some methods with instrumented ones

georgeryoung at gmail.com georgeryoung at gmail.com
Fri Jun 26 13:12:19 EDT 2015


[python 2.7, linux]
I have a python app. I cannot modify the file.  But I can import it and mess with it.  I need to perform brief tasks before and after some of the member functions.  
I'd like to do this in as clear and maintainable way as possible (no third party imports).  Here's what I have now(which works):

from newvbr import *  #get all the stuff from the newvbr app.

def perf_time(tag):  # I do a little more than this, but you get the idea.
    print >>sys.stderr, datetime.datetime.now().isoformat() + tag

def perf(tag):
    def decorator(fn):
        def wrapper(*args):
            perf_time('start %s' % tag)
            ret = fn(*args)
            perf_time('end %s' % tag)
            return ret
        return wrapper
    return decorator


I use this on various members of various classes in the newvbr app:

old_database_snapshot = VerticaSession.database_snapshot
@perf('db_snap')
def new_database_snapshot(self, name):
    old_database_snapshot(self, name)
VerticaSession.database_snapshot = new_database_snapshot

old_object_snapshot = VerticaSession.object_snapshot
@perf('obj_snap')
def new_object_snapshot(self, name):
    old_object_snapshot(self, name)
VerticaSession.object_snapshot = new_object_snapshot

main()  #do the usual stuff of the imported app, but with annotations.


This is still pretty laborious.  How can I make something roughly like:

   super_tagger(VerticaSession.database_snapshot) 

that does all the above?  I need to tag a bunch of function members like this.  I don't insist on using decorators, it just looked like that kind of problem.



More information about the Python-list mailing list