8000 gh-96663: Add a better error message for __dict__-less classes setattr by Gobot1234 · Pull Request #103232 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

gh-96663: Add a better error message for __dict__-less classes setattr #103232

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Jul 22, 2023
Prev Previous commit
Next Next commit
Try checking for a __setattr__ hook before mentioning __dict__
  • Loading branch information
Gobot1234 committed Apr 4, 2023
commit 0644b531fc7d02e07f3bb97749fb7db82f936c7b
14 changes: 13 additions & 1 deletion Lib/test/test_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import unittest


testmeths = [

# Binary operations
Expand Down Expand Up @@ -641,6 +640,14 @@ class A:
class B:
y = 0
__slots__ = ('z',)
class C:
__slots__ = ("y",)

def __setattr__(self, name, value) -> None:
if name == "z":
super().__setattr__("y", 1)
else:
super().__setattr__(name, value)

error_msg = "'A' object has no attribute 'x'"
with self.assertRaisesRegex(AttributeError, error_msg):
Expand All @@ -658,6 +665,11 @@ class B:
"'B' object has no attribute 'x' and no __dict__ for setting new attributes"
):
B().x = 0
with self.assertRaisesRegex(
AttributeError,
"'C' object has no attribute 'x'"
):
B().x = 0

error_msg = "'B' object attribute 'y' is read-only"
with self.assertRaisesRegex(AttributeError, error_msg):
Expand Down
15 changes: 11 additions & 4 deletions Objects/object.c
Original file line number Diff line number Diff line change
Expand Up @@ -1545,10 +1545,17 @@ _PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name,
}
if (dictptr == NULL) {
if (descr == NULL) {
PyErr_Format(PyExc_AttributeError,
"'%.100s' object has no attribute '%U' and no "
"__dict__ for setting new attributes",
tp->tp_name, name);
if (tp->tp_setattro == PyObject_GenericSetAttr) {
PyErr_Format(PyExc_AttributeError,
"'%.100s' object has no attribute '%U' and no "
"__dict__ for setting new attributes",
tp->tp_name, name);
}
else {
PyErr_Format(PyExc_AttributeError,
"'%.100s' object has no attribute '%U'",
tp->tp_name, name);
}
set_attribute_error_context(obj, name);
}
else {
Expand Down
0