who called a function?

Laurent Pointal laurent.pointal at laposte.net
Wed Nov 21 22:03:57 CET 2001


[posted and mailed]

<kosh at aesaeion.com> wrote in
news:mailman.1005800061.13841.python-list at python.org: 

> How can I find out what object called a function and essentially step
> back through that? At most I need to step back about 4 to 5 levels but
> it would be very useful for me to find a particular object back up the
> list and change behavior based on that. Mostly I just wants the self
> var as I step back until I find the one I want.


I have a module with functions dealing with this (Python 2.1):


#=========================================================================
def framerecextractfctmod (frame) :
    """return function name and module name from a frame record.

    Return a tuple (function name,module name).
    """
    info = inspect.getframeinfo(frame)
    fctname = info[2]
    modfilename = info[0]
    if modfilename != None :
        modname = inspect.getmodulename (modfilename)
    else :
        modname = ""

    return (fctname,modname)


And you call it with things like:
        frame = sys._getframe (1)
        name,module = framerecextractfctmod (frame)
        del frame


See _getframe documentation:
_getframe([depth]) 
Return a frame object from the call stack. If optional integer depth is 
given, return the frame object that many calls below the top of the stack. 
If that is deeper than the call stack, ValueError is raised. The default for 
depth is zero, returning the frame at the top of the call stack. 
This function should be used for internal and specialized purposes only. 





More information about the Python-list mailing list