Finding the name of your caller in PythonOne 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: import inspect
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[2] == "<module>":
return "(%s:%d)" % (fi[0], fi[1])
else:
return "%s() (%s:%d)" % (fi[2],
fi[0], fi[1])
finally:
del fr
This returns something like ' Technically we don't need to call (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.) |
These are my WanderingThoughts GettingAround This is part of CSpace, and is written by ChrisSiebenmann. * * * Atom feeds are available; see the bottom of most pages. Categories: links, linux, programming, python, snark, solaris, spam, sysadmin, tech, unix, web |