mirror of
https://github.com/python/cpython.git
synced 2025-08-03 16:39:00 +00:00
gh-99139: Improve NameError error suggestion for instances (#99140)
This commit is contained in:
parent
a0bc75e2fd
commit
99e2e60cb2
7 changed files with 92 additions and 0 deletions
|
@ -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
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue