Finding the name of your caller in Python
One of the things that would be useful in an access tracer is reporting not just what was accessed, but where it was accessed from. A basic starter for this is knowing what function called you.
CPython has enough introspection faculties to give you this information, but it's not entirely documented how to dig it out. The big tool for this is the inspect module, and we can use it to define a function:
def getcallerinfo(): fr = inspect.currentframe() try: fr = fr.f_back.f_back if fr is None: return "<no caller>" fi = inspect.getframeinfo(fr, 0) if fi == "<module>": return "(%s:%d)" % (fi, fi) else: return "%s() (%s:%d)" % (fi, fi, fi) finally: del fr
This returns something like '
barfunc() (foo.py:30)', which means that
the function that called
getcallerinfo() was called by
specifically the code at line 30 of
Technically we don't need to call
inspect.getframeinfo() to obtain
this information (we could just use
and so on directly, since they're documented), but it handles some
peculiar magic with the file name for us.
(Needless to say, this is probably specific to CPython; I would be surprised if the same code worked in Jython or IronPython or the like. Since all of this is documented, it is at least likely to be portable across different versions of CPython and to keep working in future ones.)