function call

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Mon Sep 3 11:10:54 EDT 2007


Bruno Desthuilliers a écrit :
> ianaré a écrit :
> 
>> Hey all,
>>
>> Is there a way of printing out how a function was called? In other
>> words if I do the following:
>>
>> def someFunction(self):
>>     self.someOtherFunction(var1, var2)
>>
>>
>> I would get something like "someOtherFunction: called by:
>> someFunction, args are: var1, var2"
>>
>> Thanks in advance
>>
> You may be able to solve this using a decorator (to avoid polluting your 
> code with this) and the infamous sys._getframe() hack.

Not even with sys._getframe in fact - or at least not directly !-)


import inspect

def trace(func):
     def traced(*args, **kw):
         f = inspect.currentframe(1)
         caller = inspect.getframeinfo(f)[2]
         print "%s : called by %s with %s %s" \
               % (caller, func.__name__, str(args), kw)
         return func(*args, **kw)
     return traced

@trace
def test(toto, tata=None):
     return 42

def call(toto):
     return test(toto, 24)

call("foo")

HTH



More information about the Python-list mailing list