Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 547298c

Browse files
Close #16160: Subclass support now works for types.SimpleNamespace. Thanks to RDM for noticing.
1 parent e54c718 commit 547298c

3 files changed

Lines changed: 23 additions & 12 deletions

File tree

Lib/test/test_types.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1135,6 +1135,15 @@ def test_as_dict(self):
11351135
with self.assertRaises(TypeError):
11361136
ns['spam']
11371137

1138+
def test_subclass(self):
1139+
class Spam(types.SimpleNamespace):
1140+
pass
1141+
1142+
spam = Spam(ham=8, eggs=9)
1143+
1144+
self.assertIs(type(spam), Spam)
1145+
self.assertEqual(vars(spam), {'ham': 8, 'eggs': 9})
1146+
11381147

11391148
def test_main():
11401149
run_unittest(TypesTests, MappingProxyTests, ClassCreationTests,

Misc/NEWS

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ Core and Builtins
1515
- Issue #14783: Improve int() docstring and switch docstrings for str(),
1616
range(), and slice() to use multi-line signatures.
1717

18+
- Issue #16160: Subclass support now works for types.SimpleNamespace.
19+
1820
- Issue #15379: Fix passing of non-BMP characters as integers for the charmap
1921
decoder (already working as unicode strings). Patch by Serhiy Storchaka.
2022

Objects/namespaceobject.c

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -21,19 +21,19 @@ static PyMemberDef namespace_members[] = {
2121
static PyObject *
2222
namespace_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2323
{
24-
_PyNamespaceObject *ns;
25-
ns = PyObject_GC_New(_PyNamespaceObject, &_PyNamespace_Type);
26-
if (ns == NULL)
27-
return NULL;
28-
29-
ns->ns_dict = PyDict_New();
30-
if (ns->ns_dict == NULL) {
31-
Py_DECREF(ns);
32-
return NULL;
24+
PyObject *self;
25+
26+
assert(type != NULL && type->tp_alloc != NULL);
27+
self = type->tp_alloc(type, 0);
28+
if (self != NULL) {
29+
_PyNamespaceObject *ns = (_PyNamespaceObject *)self;
30+
ns->ns_dict = PyDict_New();
31+
if (ns->ns_dict == NULL) {
32+
Py_DECREF(ns);
33+
return NULL;
34+
}
3335
}
34-
35-
PyObject_GC_Track(ns);
36-
return (PyObject *)ns;
36+
return self;
3737
}
3838

3939

0 commit comments

Comments
 (0)