Skip to content

Commit 9796856

Browse files
authored
gh-143636: fix a crash when calling __replace__ on invalid SimpleNamespace instances (#143655)
1 parent 51e8acf commit 9796856

File tree

3 files changed

+26
-0
lines changed

3 files changed

+26
-0
lines changed

Lib/test/test_types.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2168,6 +2168,21 @@ class Spam(types.SimpleNamespace):
21682168
self.assertIs(type(spam2), Spam)
21692169
self.assertEqual(vars(spam2), {'ham': 5, 'eggs': 9})
21702170

2171+
def test_replace_invalid_subtype(self):
2172+
# See https://github.com/python/cpython/issues/143636.
2173+
class MyNS(types.SimpleNamespace):
2174+
def __new__(cls, *args, **kwargs):
2175+
if created:
2176+
return 12345
2177+
return super().__new__(cls)
2178+
2179+
created = False
2180+
ns = MyNS()
2181+
created = True
2182+
err = (r"^expect types\.SimpleNamespace type, "
2183+
r"but .+\.MyNS\(\) returned 'int' object")
2184+
self.assertRaisesRegex(TypeError, err, copy.replace, ns)
2185+
21712186
def test_fake_namespace_compare(self):
21722187
# Issue #24257: Incorrect use of PyObject_IsInstance() caused
21732188
# SystemError.
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix a crash when calling :class:`SimpleNamespace.__replace__()
2+
<types.SimpleNamespace>` on non-namespace instances. Patch by Bénédikt Tran.

Objects/namespaceobject.c

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ typedef struct {
1313
} _PyNamespaceObject;
1414

1515
#define _PyNamespace_CAST(op) _Py_CAST(_PyNamespaceObject*, (op))
16+
#define _PyNamespace_Check(op) PyObject_TypeCheck((op), &_PyNamespace_Type)
1617

1718

1819
static PyMemberDef namespace_members[] = {
@@ -234,6 +235,14 @@ namespace_replace(PyObject *self, PyObject *args, PyObject *kwargs)
234235
if (!result) {
235236
return NULL;
236237
}
238+
if (!_PyNamespace_Check(result)) {
239+
PyErr_Format(PyExc_TypeError,
240+
"expect %N type, but %T() returned '%T' object",
241+
&_PyNamespace_Type, self, result);
242+
Py_DECREF(result);
243+
return NULL;
244+
}
245+
237246
if (PyDict_Update(((_PyNamespaceObject*)result)->ns_dict,
238247
((_PyNamespaceObject*)self)->ns_dict) < 0)
239248
{

0 commit comments

Comments
 (0)