diff options
author | Pablo Galindo Salgado <Pablogsal@gmail.com> | 2022-11-06 13:52:06 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-11-06 13:52:06 (GMT) |
commit | 99e2e60cb25bfcf77ba1386d331cfa85864e6a65 (patch) | |
tree | 9aec45b4196922f64b17f82a52761514347c8d25 /Python | |
parent | a0bc75e2fdd53680cb147881bcb3754bd56aa2fa (diff) | |
download | cpython-99e2e60cb25bfcf77ba1386d331cfa85864e6a65.zip cpython-99e2e60cb25bfcf77ba1386d331cfa85864e6a65.tar.gz cpython-99e2e60cb25bfcf77ba1386d331cfa85864e6a65.tar.bz2 |
gh-99139: Improve NameError error suggestion for instances (#99140)
Diffstat (limited to 'Python')
-rw-r--r-- | Python/suggestions.c | 23 |
1 files changed, 23 insertions, 0 deletions
diff --git a/Python/suggestions.c b/Python/suggestions.c index 82376b6..239245d 100644 --- a/Python/suggestions.c +++ b/Python/suggestions.c @@ -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 |