How to get the method/function which called a function?
holger krekel
pyth at devel.trillke.net
Wed Jul 24 12:14:30 EDT 2002
Alessandro Iob wrote:
> def log(msg):
> caller = GET_CALLER()
> print repr(caller), msg
>
> class A:
> def t(self):
> log('a message')
>
> a = A()
> a.t() # prints "<bound method A.t of <__main__.A instance at 0x805bb64>>
> a message"
>
> How can I implement the "GET_CALLER()" function in "log()" ?
You can't.
Basically you can get to the namespaces of your callers, though.
import inspect
pframe = inspect.currentframe(2) # caller's caller frame
local2self = pframe.f_locals['self']
But you can't get to the name of the A.t method (i.e. 't') this way.
The execution frame only knows about the *code* object beeing executed
and not the orginal name ('t') which bound to that code object. It does
know about the line number, though.
You could try to use the line-numbers in the execution frames to get
to the source code ('inspect.getsource') and try to extract names.
I don't recommend going this way as it is very hard to get it to
work reliably. And it has little chance to work across language boundaries
(e.g with C-coded extensions).
regards,
holger
More information about the Python-list
mailing list