The call stack

class CallStack(frames)

Represents the call stack - a series of CallFrame instances.

This class can be used like a read-only list. It supports iteration, indexing, membership testing, etc. The root frame is first in the list, at index 0.

Because holding references to call frames can result in reference cycles, it’s recommended to use CallStack objects as context managers. Upon exit, the frame objects are released and the CallStack becomes empty:

with CallStack.current() as stack:
    ...  # do something with the stack
# at this point, len(stack) is 0
__init__(frames)

Creates a new CallStack from the given frame objects.

classmethod current()

Get the current call stack.

classmethod from_frame(frame)

Creates a CallStack containing frame and all its parents.

Parameters

frame – The last frame in the call stack

Returns

A new CallStack instance

class CallFrame(frame)

Represents a call frame - an element of the call stack. It keeps track of local and closure variables.

Although CallFrame does not inherit from types.FrameType, they can be used just like regular frame objects.

Note that storing CallFrames in variables can create reference cycles where a frame contains a reference to itself. To avoid this, CallFrames can be used as context managers - upon exit, the reference to the underlying frame object is released:

with CallFrame.current() as frame:
    ...  # do stuff with the frame
# at this point, the frame has become unusable
__init__(frame)

Creates a new CallFrame from a CallFrame or types.FrameType object.

classmethod current()

Retrieves the current call frame.

classmethod from_frame(frame)

Creates a new CallFrame from a CallFrame or types.FrameType object.

This is equivalent to calling CallFrame(frame).

property parent

Returns the next frame one level higher on the call stack.

property builtins

The builtins seen by this frame

property globals

The global scope seen by this frame

property locals

The frame’s local variable scope

property code_object

The code object being executed in this frame

property file_name

The name of the file in which this frame’s code was defined

property scope_name

The name of the scope in which this frame’s code was defined. In case of a function, the function’s name. In case of a class, the class’s name. In any other case, whichever name the interpreter assigned to that scope.

resolve_name(name)

Resolves a variable name, returning the variable’s value.

Note

Closure variables don’t have a named associated with them, which means they cannot be looked up with this function.

This includes variables marked as nonlocal.

Returns

The value mapped to the given name

Raises

NameError – If no matching variable is found

get_surrounding_function()

Finds and returns the function in which the code of this frame was defined.

If the function can’t be found, None is returned.

Returns

The calling function object or None if it can’t be found