On Jun 27, 2:42 pm, Matthew Peter <[EMAIL PROTECTED]> wrote: > Is it possible to print the function calls to a module? Like: > > test.py > import mymod > print mymod.x() > > mymod.py > # each time a function is called we print out the called function and module > print 'Func call: %s from %s' % (???, ???) > > def x(): > return 'hello' > > Where would I pick up the ??? variables? A brief example would be nice too :) > Thanks > in advance!
You can use a decorator to wrap the function. You can use sys._getframe or inspect.stack to get information about the caller. The examples from the decorator module are very useful: http://www.phyast.pitt.edu/~micheles/python/documentation.html If for some reason you can't edit mymod.py to add the decorators, you can still wrap the function: import mymod import inspect try: from functools import update_wrapper except ImportError: def decorator_trace(f): def newf(): caller = inspect.stack()[1] print 'Caller is line %d of %s' % (caller[2], caller[1]) print 'Calling: %s from %s' % (f.__name__, f.__module__) return f() newf.__name__ = f.__name__ newf.__dict__.update(f.__dict__) newf.__doc__ = f.__doc__ newf.__module__ = f.__module__ return newf else: def decorator_trace(f): def newf(): caller = inspect.stack()[1] print 'Caller is line %d of %s' % (caller[2], caller[1]) print 'Calling: %s from %s' % (f.__name__, f.__module__) return f() return update_wrapper(newf, f) mymod.x = decorator_trace(mymod.x) greetings = mymod.x() print greetings but this approach has the shortcoming mentioned in the article. -- Hope this helps, Steven -- http://mail.python.org/mailman/listinfo/python-list