who called a function?

Hans Nowak wurmy at earthlink.net
Thu Nov 15 18:21:27 CET 2001


kosh at aesaeion.com wrote:
> 
> 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.

This comes from my now-dysfunctional snippet collection... It doesn't
step
back some levels like you want, but it may be helpful...

------
# 294.py
# Author: Michael P. Reilly
# Subject: Function which knows who has called it
# Packages: miscellaneous.introspection

"""
: Is if possible in Python to have a function that prints the name
: of the function that called it. (I'm thinking of using this in
: some debugging code I want to write).

The information is captured in the frames in the traceback.
"""

def you_rang():
  import sys
  try:
    raise RuntimeError
  except RuntimeError:
    exc, val, tb = sys.exc_info()
    frame = tb.tb_frame.f_back
    del exc, val, tb
  try:
    return frame.f_back.f_code.co_name
  except AttributeError:  # called from the top
    return None

def f():
  WhoCalledMe = you_rang()
  print WhoCalledMe

def p():    # p calls f
    f()

p()
------

HTH,

--Hans



More information about the Python-list mailing list