gh-99139: Improve NameError error suggestion for instances (#99140)

This commit is contained in:
Pablo Galindo Salgado 2022-11-06 13:52:06 +00:00 committed by GitHub
parent a0bc75e2fd
commit 99e2e60cb2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 92 additions and 0 deletions

View file

@ -1,5 +1,6 @@
#include "Python.h"
#include "pycore_frame.h"
#include "pycore_runtime_init.h" // _Py_ID()
#include "pycore_pyerrors.h"
#include "pycore_code.h" // _PyCode_GetVarnames()
@ -226,6 +227,24 @@ get_suggestions_for_name_error(PyObject* name, PyFrameObject* frame)
return NULL;
}
// Are we inside a method and the instance has an attribute called 'name'?
if (PySequence_Contains(dir, &_Py_ID(self)) > 0) {
PyObject* locals = PyFrame_GetLocals(frame);
if (!locals) {
goto error;
}
PyObject* self = PyDict_GetItem(locals, &_Py_ID(self)); /* borrowed */
Py_DECREF(locals);
if (!self) {
goto error;
}
if (PyObject_HasAttr(self, name)) {
Py_DECREF(dir);
return PyUnicode_FromFormat("self.%S", name);
}
}
PyObject *suggestions = calculate_suggestions(dir, name);
Py_DECREF(dir);
if (suggestions != NULL) {
@ -250,6 +269,10 @@ get_suggestions_for_name_error(PyObject* name, PyFrameObject* frame)
Py_DECREF(dir);
return suggestions;
error:
Py_DECREF(dir);
return NULL;
}
static bool