finding the object corresponding to a stack frame

E

Eric Snow

For any given stack frame, the corresponding code object is derived
most immediately from either a module [definition], a class
definition, or function definition. I want to be able to determine
the specific module, class, or function object for any arbitrary
code/frame object. For modules it is pretty straightforward. For
classes, the object doesn't exist yet, but I can work around that.

Lastly, for functions it is not nearly as simple as I had hoped. If
the function is defined in the global namespace then the solution is
relatively trivial, using the inspect module:

def get_context():
frame = inspect.currentframe().f_back
if frame.f_code.co_name == "<module>":
return sys.modules[frame.f_locals["__name__"]]
return frame.f_globals.get(frame.f_code.co_name)

def f():
context = get_context()
f()

However, under other conditions it is not so easy:

- the function is nested inside another,
- the code object is shared between multiple functions,
- the function is accessed as an attribute of some other object and
thus is not bound by its name in the easy search namespaces (like
globals),
- others?

I'm trying to see if there is a way to work through these issues. It
would be great if objects knew under which object each was defined,
but that is a bigger question for another time. Right now I would
just settle for a frame object knowing the object for which it is
running, particularly for functions. However, judging by similar
questions found while researching this, I'm not holding my breath.

Any ideas?

-eric
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,058
Latest member
QQXCharlot

Latest Threads

Top