Function calls and reflection

holger krekel pyth at devel.trillke.net
Sun Jan 5 17:19:52 EST 2003


Boethius wrote:
> Can a function tell which function / method called it?

you can get to the name of the caller's function with 
something like 
(python2.2)
    >>> def f():
           g()

    >>> def g():
           import inspect
           print inspect.currentframe(1).f_code.co_name

    >>> f()
    f

But ASFAIK there is no direct way to get to the function
*object*.  With the following snippet you might get
to a calling function if it is defined at the module level
(e.g. it doesn't get to instance methods).

def determine_calling_function():
    import inspect
    frame = inspect.currentframe(1)
    return frame.f_globals[frame.f_code.co_name]

I am not sure if the frame object provides enough
information to unambigously get to the object
currently executing in it.  

regards,

    holger


-- 
"Why are people killing each other when there is so much fun stuff
 to be had through friendly cooperation?" (Bengt Richter on c.l.py)





More information about the Python-list mailing list