Invoker of a method

Alex Martelli aleaxit at yahoo.com
Sun Oct 24 04:56:28 EDT 2004


Andre Meyer <meyer at acm.org> wrote:

> Hi Pythoneers
> 
> In an application I am developing I want to register the invoker of a
> method call. Is there any way to find out who is invoking an object's
> method? I do not want to rely on the caller telling the callee his name
> explicitly.

inspect.currentframe lets you inspect the call frames up the stack,
including (of course) the caller's one; same as sys._getframe.  However,
I suggest you reconsider using this in production code, as opposed to
debugging or other development-framework tasks.  As the docstring says:

'''
This function should be used for internal and specialized purposes only.
'''

It's not an issue of doing what you desire with one function or another;
if you do it at all, inspect.currentframe is appropriate.  Rather, the
issue is that a function _shouldn't_ go rooting around in frames up the
stack, except for debugging and other instrumentation purposes: such
"black magic" behavior is not recommended, it damages the important
quality of transparence.

Still, Python does give you plenty enough rope to shoot yourself in the
foot, as befits the principles in the "Spirit of C" which Python also
follows: trust the programmer, don't stop the programmer from doing
something that _needs_ to be done.  Just make sure about that 'needs'!-)


Alex



More information about the Python-list mailing list