8

The documentation for the inspect module says:

When the following functions return “frame records,” each record is a named tuple FrameInfo(frame, filename, lineno, function, code_context, index). The tuple contains the frame object, the filename, the line number of the current line, the function name, a list of lines of context from the source code, and the index of the current line within that list.

What is actually a "frame object"? I was hoping to use this frame object to get a variable's value from the caller's globals():

import my_util

a=3
my_util.get_var('a')

and my_util.py

import inspect

def get_var(name):
    print(inspect.stack()[1][0])
Håkon Hægland
  • 39,012
  • 21
  • 81
  • 174
  • 2
    While the docs don't explain what a frame object actually _is_, they do at least describe its structure in [this table](https://docs.python.org/3/library/inspect.html#types-and-members) (scroll down to "frame"). Looks like you can just do `return inspect.stack()[1][0].f_globals[name]`. – Aran-Fey May 22 '17 at 08:31
  • @Rawing Thanks, this seems to work! – Håkon Hægland May 22 '17 at 08:34
  • 2
    A small addition, if you want to dive a little deeper in this I found this SO thread very useful - http://stackoverflow.com/questions/23848391/what-is-the-difference-between-a-stack-and-a-frame – SRC May 22 '17 at 08:45

1 Answers1

14

from https://docs.python.org/3/library/inspect.html#types-and-members:

frame   f_back      next outer frame object (this frame’s caller)
        f_builtins  builtins namespace seen by this frame
        f_code      code object being executed in this frame
        f_globals   global namespace seen by this frame
        f_lasti     index of last attempted instruction in bytecode
        f_lineno    current line number in Python source code
        f_locals    local namespace seen by this frame
        f_restricted    0 or 1 if frame is in restricted execution mode
        f_trace     tracing function for this frame, or None

therefore to get some globals in your my_util.py:

import inspect

def get_var(name):
    print(inspect.stack()[1][0].f_globals[name])
Håkon Hægland
  • 39,012
  • 21
  • 81
  • 174
Fabian
  • 531
  • 4
  • 11