[Python-checkins] cpython: complain when a class variable shadows a name in __slots__ (closes #12766)

benjamin.peterson python-checkins at python.org
Wed Aug 17 01:53:37 CEST 2011


http://hg.python.org/cpython/rev/45b63a8a76c9
changeset:   71888:45b63a8a76c9
user:        Benjamin Peterson <benjamin at python.org>
date:        Tue Aug 16 18:53:26 2011 -0500
summary:
  complain when a class variable shadows a name in __slots__ (closes #12766)

files:
  Lib/test/test_descr.py |  8 ++++++++
  Misc/NEWS              |  3 +++
  Objects/typeobject.c   |  6 ++++++
  3 files changed, 17 insertions(+), 0 deletions(-)


diff --git a/Lib/test/test_descr.py b/Lib/test/test_descr.py
--- a/Lib/test/test_descr.py
+++ b/Lib/test/test_descr.py
@@ -4253,6 +4253,14 @@
         foo = Foo()
         str(foo)
 
+    def test_slot_shadows_class(self):
+        with self.assertRaises(ValueError) as cm:
+            class X:
+                __slots__ = ["foo"]
+                foo = None
+        m = str(cm.exception)
+        self.assertEqual("'foo' in __slots__ conflicts with class variable", m)
+
 class DictProxyTests(unittest.TestCase):
     def setUp(self):
         class C(object):
diff --git a/Misc/NEWS b/Misc/NEWS
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -10,6 +10,9 @@
 Core and Builtins
 -----------------
 
+- Issue #12766: Raise an ValueError when creating a class with a class variable
+  that conflicts with a name in __slots__.
+
 - Issue #12266: Fix str.capitalize() to correctly uppercase/lowercase
   titlecased and cased non-letter characters.
 
diff --git a/Objects/typeobject.c b/Objects/typeobject.c
--- a/Objects/typeobject.c
+++ b/Objects/typeobject.c
@@ -2094,6 +2094,12 @@
             if (!tmp)
                 goto bad_slots;
             PyList_SET_ITEM(newslots, j, tmp);
+            if (PyDict_GetItem(dict, tmp)) {
+                PyErr_Format(PyExc_ValueError,
+                             "%R in __slots__ conflicts with class variable",
+                             tmp);
+                goto bad_slots;
+            }
             j++;
         }
         assert(j == nslots - add_dict - add_weak);

-- 
Repository URL: http://hg.python.org/cpython


More information about the Python-checkins mailing list