]> granicus.if.org Git - python/commitdiff
Close #16160: Subclass support now works for types.SimpleNamespace. Thanks to RDM...
authorEric Snow <ericsnowcurrently@gmail.com>
Wed, 17 Oct 2012 05:35:38 +0000 (22:35 -0700)
committerEric Snow <ericsnowcurrently@gmail.com>
Wed, 17 Oct 2012 05:35:38 +0000 (22:35 -0700)
Lib/test/test_types.py
Misc/NEWS
Objects/namespaceobject.c

index 3f5ac98a0e328fbcbd6c7a2e2199b062e1f3e433..3ee4c6bc5fdc3657900cfa116f11f09e7426db7b 100644 (file)
@@ -1135,6 +1135,15 @@ class SimpleNamespaceTests(unittest.TestCase):
         with self.assertRaises(TypeError):
             ns['spam']
 
+    def test_subclass(self):
+        class Spam(types.SimpleNamespace):
+            pass
+
+        spam = Spam(ham=8, eggs=9)
+
+        self.assertIs(type(spam), Spam)
+        self.assertEqual(vars(spam), {'ham': 8, 'eggs': 9})
+
 
 def test_main():
     run_unittest(TypesTests, MappingProxyTests, ClassCreationTests,
index 798ce7828072c78f88d72926149fff8108e8589b..944141254f618d2bf7f0226f5c5c985c4b273dda 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -15,6 +15,8 @@ Core and Builtins
 - Issue #14783: Improve int() docstring and switch docstrings for str(),
   range(), and slice() to use multi-line signatures.
 
+- Issue #16160: Subclass support now works for types.SimpleNamespace.
+
 - Issue #15379: Fix passing of non-BMP characters as integers for the charmap
   decoder (already working as unicode strings).  Patch by Serhiy Storchaka.
 
index 753874c3cbe5231df1ce60bf1285d0a8c5c3c776..ff278d33474a2bf7c800be687a1acf058431a5f0 100644 (file)
@@ -21,19 +21,19 @@ static PyMemberDef namespace_members[] = {
 static PyObject *
 namespace_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
 {
-    _PyNamespaceObject *ns;
-    ns = PyObject_GC_New(_PyNamespaceObject, &_PyNamespace_Type);
-    if (ns == NULL)
-        return NULL;
-
-    ns->ns_dict = PyDict_New();
-    if (ns->ns_dict == NULL) {
-        Py_DECREF(ns);
-        return NULL;
+    PyObject *self;
+
+    assert(type != NULL && type->tp_alloc != NULL);
+    self = type->tp_alloc(type, 0);
+    if (self != NULL) {
+        _PyNamespaceObject *ns = (_PyNamespaceObject *)self;
+        ns->ns_dict = PyDict_New();
+        if (ns->ns_dict == NULL) {
+            Py_DECREF(ns);
+            return NULL;
+        }
     }
-
-    PyObject_GC_Track(ns);
-    return (PyObject *)ns;
+    return self;
 }