]> granicus.if.org Git - python/commitdiff
Raise a TypeError if conflicting positional and named arguments are
authorThomas Heller <theller@ctypes.org>
Wed, 16 Jan 2008 19:37:33 +0000 (19:37 +0000)
committerThomas Heller <theller@ctypes.org>
Wed, 16 Jan 2008 19:37:33 +0000 (19:37 +0000)
passed to a Structure or Union constructor.

Lib/ctypes/test/test_structures.py
Misc/NEWS
Modules/_ctypes/_ctypes.c

index f9a11096938d58cc0cc9e20df7436bbe636dd33a..3005e829b3abf65e8fde90e90acfd5f4dd67c856 100644 (file)
@@ -215,6 +215,15 @@ class StructureTestCase(unittest.TestCase):
         # too long
         self.assertRaises(ValueError, Person, "1234567", 5)
 
+    def test_conflicting_initializers(self):
+        class POINT(Structure):
+            _fields_ = [("x", c_int), ("y", c_int)]
+        # conflicting positional and keyword args
+        self.assertRaises(TypeError, POINT, 2, 3, x=4)
+        self.assertRaises(TypeError, POINT, 2, 3, y=4)
+
+        # Should this raise TypeError instead?
+        self.assertRaises(ValueError, POINT, 2, 3, 4)
 
     def test_keyword_initializers(self):
         class POINT(Structure):
index 0a7d00c80312f555097d11444b05956046cf6eb3..29bd3dd939751581fdb5bc5bd33e269634d305bf 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -364,6 +364,9 @@ Core and builtins
 Library
 -------
 
+- Issue #1831: ctypes now raises a TypeError if conflicting positional
+  and named arguments are passed to a Structure or Union initializer.
+
 - Convert the internal ctypes array type cache to a WeakValueDict so
   that array types do not live longer than needed.
 
index 1ff8e12ce5c17b25f35a5723c977b200eb00969f..8c6619489f7d24d27d1e63e8614f1d6a7a40d9c2 100644 (file)
@@ -3578,6 +3578,21 @@ Struct_init(PyObject *self, PyObject *args, PyObject *kwds)
                                return IBUG("_fields_[i][0] failed");
                        }
 
+                       if (kwds && PyDict_GetItem(kwds, name)) {
+                               char *field = PyString_AsString(name);
+                               if (field == NULL) {
+                                       PyErr_Clear();
+                                       field = "???";
+                               }
+                               PyErr_Format(PyExc_TypeError,
+                                            "duplicate values for field %s",
+                                            field);
+                               Py_DECREF(pair);
+                               Py_DECREF(name);
+                               Py_DECREF(fields);
+                               return -1;
+                       }
+
                        val = PyTuple_GET_ITEM(args, i);
                        if (-1 == PyObject_SetAttr(self, name, val)) {
                                Py_DECREF(pair);