Finding the calling method (or caller)

Chad Netzer cnetzer at mail.arc.nasa.gov
Thu Jan 16 20:31:19 EST 2003


On Thursday 16 January 2003 16:56, Aahz wrote:

> Why do you want to know this?  There's likely to be a better way than
> using sys._getframe().

I use introspection techniques like this to enforce calling through the 
"public" api, and not the private.

Often, I'll have public API methods, say api.a(), api.b(), api.c(), 
etc.  But to actually implement it, underneath the hood, I'll have 
multiple objects with the same function names, ie:  foo.a(), bar.b(), 
eggs.c(), etc.

When I'm coding, I want to use the public API as well, rather than 
directly calling the underlying implementation functions.  This allows 
me to do things like record scripts of the API calls, for replay, or 
otherwise put a layer between it and the implementation.  I don't want 
to have calls going on behind the back of the API that aren't recorded 
(except those that truly are internal)

Anyway, that is one way that I use it.  I've actually wondered if there 
were other, perhaps better techniques that didn't involve name 
mangling.  But this kind of thing works well for me.

But, as to the actual question of the original, I'm not sure how to 
find the method that was called.  I usually just enforce the caller, 
and trust that I've coded the proper chain of methods. :)

Right now I can make sure that foo.a() is called by api.a(), but I 
don't verify that foo.b() is called by api.b() rather than api.a().  I 
think that is a bit too introspective and fragile.  Better to just have 
the proper tests of the API to verify that I didn't make such a typo...

BTW. I do the actual caller verification with kludges like:

def _only_callable_from_object( calling_obj ):
    # Go up two frames, since this call adds an extra stack frame
    two_frames_up = inspect.currentframe().f_back.f_back
    return (two_frames_up.f_locals[ 'self' ] == calling_obj)

I could make it more robust, I suppose, but it fits my current needs.

-- 
Bay Area Python Interest Group - http://www.baypiggies.net/

Chad Netzer






More information about the Python-list mailing list