1

I'm parsing some Python bytecode to get the name of the variable an expression is assigned to. I think that this would be much easier if I could read the contents of the stack of a Python frame.

I've tried it with this C extension, but I always get ValueError: no value stack, so the PyFrameObject::f_stackop is always NULL.

static PyObject*
_get_frame_valuestack(PyObject* self, PyObject* args)
{
  PyFrameObject* frame;
  if (!PyArg_ParseTuple(args, "O", &frame)) {
    return NULL;
  }

  if (((PyObject*) frame)->ob_type != &PyFrame_Type) {
    PyErr_SetString(PyExc_TypeError, "expected frame object");
    return NULL;
  }

  if (frame->f_valuestack == NULL || frame->f_stacktop == NULL) {
    PyErr_SetString(PyExc_ValueError, "no value stack");
    return NULL;
  }

  PyObject* list = PyList_New(0);
  PyObject** p;
  for (p = frame->f_valuestack; p < frame->f_stacktop; ++p) {
    PyList_Append(list, *p);
  }
  return list;
}

Here's a test snippet.

def foo():
  print(_utils.get_frame_valuestack(sys._getframe(1)))
  return 40

var = 2 + foo()

I'd expect something like [2] to be printed in foo(). The actual result could differ depending on how its really implemented.

Apparently f_valuestack is not what I am actually looking for. Is there a way I can retreive the contents of a frame's stack?

Niklas R
  • 16,299
  • 28
  • 108
  • 203

0 Answers0