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


Groups > comp.lang.python > #10846

finding the object corresponding to a stack frame

Date 2011-08-04 01:49 -0600
Subject finding the object corresponding to a stack frame
From Eric Snow <ericsnowcurrently@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.1881.1312444181.1164.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

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

csiph-web