Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #10846 > unrolled thread

finding the object corresponding to a stack frame

Started byEric Snow <ericsnowcurrently@gmail.com>
First post2011-08-04 01:49 -0600
Last post2011-08-04 01:49 -0600
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python


Contents

  finding the object corresponding to a stack frame Eric Snow <ericsnowcurrently@gmail.com> - 2011-08-04 01:49 -0600

#10846 — finding the object corresponding to a stack frame

FromEric Snow <ericsnowcurrently@gmail.com>
Date2011-08-04 01:49 -0600
Subjectfinding the object corresponding to a stack frame
Message-ID<mailman.1881.1312444181.1164.python-list@python.org>
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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web