gh-91248: Add PyFrame_GetVar() function (#95712)

Add PyFrame_GetVar() and PyFrame_GetVarString() functions to get a
frame variable by its name.

Move PyFrameObject C API tests from test_capi to test_frame.
This commit is contained in:
Victor Stinner 2022-11-08 17:40:27 +01:00 committed by GitHub
parent acf4d5d5bd
commit 4d5fcca273
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 126 additions and 22 deletions

View file

@ -1430,4 +1430,34 @@ _PyEval_BuiltinsFromGlobals(PyThreadState *tstate, PyObject *globals)
return _PyEval_GetBuiltins(tstate);
}
PyObject *
PyFrame_GetVar(PyFrameObject *frame, PyObject *name)
{
PyObject *locals = PyFrame_GetLocals(frame);
if (locals == NULL) {
return NULL;
}
PyObject *value = PyDict_GetItemWithError(locals, name);
Py_DECREF(locals);
if (value == NULL) {
if (PyErr_Occurred()) {
return NULL;
}
PyErr_Format(PyExc_NameError, "variable %R does not exist", name);
return NULL;
}
return Py_NewRef(value);
}
PyObject *
PyFrame_GetVarString(PyFrameObject *frame, const char *name)
{
PyObject *name_obj = PyUnicode_FromString(name);
if (name_obj == NULL) {
return NULL;
}
PyObject *value = PyFrame_GetVar(frame, name_obj);
Py_DECREF(name_obj);
return value;
}