[Tutor] Who called me?

Kent Johnson kent37 at tds.net
Tue Nov 8 21:46:48 CET 2005


Kent Johnson wrote:
> Bill Campbell wrote:
> 
>>Is there a way in python for a method to determine its parent?
>>
>>In particular, I'm working with SimpleXMLRPCServer, and would
>>like to be able to find the client_address in the routine that
>>has been dispatched.  I know that client_address is an attribute
>>of the handler class instance, but don't know how to get to that.
> 
> 
> You can inspect the stack frame to find this out. Search the online cookbook for _getframe - I don't see one recipe that does exactly what you want but the pieces are there.
> http://aspn.activestate.com/ASPN/Cookbook/Python

OK here is a simple module that shows callers on the stack. 

import sys

def showFrame(f):
    print 'Name =', f.f_code.co_name
    for k, v in f.f_locals.iteritems():
        print '   ', k, '=', v
    print

def whereAmI():
    i=1
    while True:
        try:
            f = sys._getframe(i)
            showFrame(f)
            i += 1
        except ValueError:
            break

if __name__ == '__main__':
    def foo(a):
        bar = 'baz'
        zap = 3
        whereAmI()

    def bar():
        foo(3)

    bar()

When I run this it prints 

Name = foo
    a = 3
    bar = baz
    zap = 3

Name = bar

Name = ?
    bar = <function bar at 0x008E9070>
    showFrame = <function showFrame at 0x008E0A30>
    __builtins__ = <module '__builtin__' (built-in)>
    __file__ = F:\Tutor\ShowStack.py
    sys = <module 'sys' (built-in)>
    whereAmI = <function whereAmI at 0x008E08B0>
    __name__ = __main__
    foo = <function foo at 0x008E9030>
    __doc__ =  Show stuff from the stack frame 


HOWEVER, I don't think this is a good solution to your problem - it's quite a fragile hack. Better would be to find a way to pass the information you need to your function. For example, from a quick look at the code for SimpleXMLRPCServer, it looks like you could subclass SimpleXMLRPCServer and make your own _dispatch() method that adds client_address to the parameter list, then all your functions would be passed the client_address. Or even specialize it so that just one special function gets this treatment.

Kent



More information about the Tutor mailing list