mirror of
https://github.com/python/cpython.git
synced 2026-05-06 04:37:33 -04:00
gh-143636: fix a crash when calling `__replace__ on invalid SimpleNamespace` instances (#143655)
This commit is contained in:
@@ -2168,6 +2168,21 @@ class SimpleNamespaceTests(unittest.TestCase):
|
||||
self.assertIs(type(spam2), Spam)
|
||||
self.assertEqual(vars(spam2), {'ham': 5, 'eggs': 9})
|
||||
|
||||
def test_replace_invalid_subtype(self):
|
||||
# See https://github.com/python/cpython/issues/143636.
|
||||
class MyNS(types.SimpleNamespace):
|
||||
def __new__(cls, *args, **kwargs):
|
||||
if created:
|
||||
return 12345
|
||||
return super().__new__(cls)
|
||||
|
||||
created = False
|
||||
ns = MyNS()
|
||||
created = True
|
||||
err = (r"^expect types\.SimpleNamespace type, "
|
||||
r"but .+\.MyNS\(\) returned 'int' object")
|
||||
self.assertRaisesRegex(TypeError, err, copy.replace, ns)
|
||||
|
||||
def test_fake_namespace_compare(self):
|
||||
# Issue #24257: Incorrect use of PyObject_IsInstance() caused
|
||||
# SystemError.
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
Fix a crash when calling :class:`SimpleNamespace.__replace__()
|
||||
<types.SimpleNamespace>` on non-namespace instances. Patch by Bénédikt Tran.
|
||||
@@ -13,6 +13,7 @@ typedef struct {
|
||||
} _PyNamespaceObject;
|
||||
|
||||
#define _PyNamespace_CAST(op) _Py_CAST(_PyNamespaceObject*, (op))
|
||||
#define _PyNamespace_Check(op) PyObject_TypeCheck((op), &_PyNamespace_Type)
|
||||
|
||||
|
||||
static PyMemberDef namespace_members[] = {
|
||||
@@ -234,6 +235,14 @@ namespace_replace(PyObject *self, PyObject *args, PyObject *kwargs)
|
||||
if (!result) {
|
||||
return NULL;
|
||||
}
|
||||
if (!_PyNamespace_Check(result)) {
|
||||
PyErr_Format(PyExc_TypeError,
|
||||
"expect %N type, but %T() returned '%T' object",
|
||||
&_PyNamespace_Type, self, result);
|
||||
Py_DECREF(result);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
if (PyDict_Update(((_PyNamespaceObject*)result)->ns_dict,
|
||||
((_PyNamespaceObject*)self)->ns_dict) < 0)
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user