finding the object corresponding to a stack frame

Eric Snow ericsnowcurrently at gmail.com
Thu Aug 4 03:49:39 EDT 2011


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



More information about the Python-list mailing list