[Numpy-svn] r8143 - trunk/numpy/core/src/multiarray

numpy-svn@scip... numpy-svn@scip...
Sat Feb 20 12:07:10 CST 2010


Author: ptvirtan
Date: 2010-02-20 12:07:10 -0600 (Sat, 20 Feb 2010)
New Revision: 8143

Modified:
   trunk/numpy/core/src/multiarray/arraytypes.c.src
Log:
3K: BUG: cast any object to unicode/bytes in UNICODE/STRING_setitem also for Py3, similarly as it is done in Py2

This makes UNICODE_setitem and STRING_setitem work similarly as on
Python 2 -- uses ASCII codec -- I judge this useful for compatibility
reasons.

Modified: trunk/numpy/core/src/multiarray/arraytypes.c.src
===================================================================
--- trunk/numpy/core/src/multiarray/arraytypes.c.src	2010-02-20 18:06:53 UTC (rev 8142)
+++ trunk/numpy/core/src/multiarray/arraytypes.c.src	2010-02-20 18:07:10 UTC (rev 8143)
@@ -345,7 +345,14 @@
         PyErr_Clear();
     }
 #if defined(NPY_PY3K)
-    if ((temp=PyUnicode_FromObject(op)) == NULL) {
+    if (PyBytes_Check(op)) {
+        /* Try to decode from ASCII */
+        temp = PyUnicode_FromEncodedObject(op, "ASCII", "strict");
+        if (temp == NULL) {
+            return -1;
+        }
+    }
+    else if ((temp=PyObject_Str(op)) == NULL) {
 #else
     if ((temp=PyObject_Unicode(op)) == NULL) {
 #endif
@@ -428,13 +435,36 @@
         PyErr_Clear();
     }
 #if defined(NPY_PY3K)
-    if ((temp = PyObject_Bytes(op)) == NULL) {
+    if (PyUnicode_Check(op)) {
+        /* Assume ASCII codec -- function similarly as Python 2 */
+        temp = PyUnicode_AsASCIIString(op);
+        if (temp == NULL) return -1;
+    }
+    else if (PyBytes_Check(op)) {
+        temp = PyObject_Bytes(op);
+        if (temp == NULL) {
+            return -1;
+        }
+    }
+    else {
+        /* Emulate similar casting behavior as on Python 2 */
+        PyObject *str;
+        str = PyObject_Str(op);
+        if (str == NULL) {
+            return -1;
+        }
+        temp = PyUnicode_AsASCIIString(str);
+        Py_DECREF(str);
+        if (temp == NULL) {
+            return -1;
+        }
+    }
 #else
     if ((temp = PyObject_Str(op)) == NULL) {
-#endif
         return -1;
     }
-    if (PyString_AsStringAndSize(temp, &ptr, &len) == -1) {
+#endif
+    if (PyBytes_AsStringAndSize(temp, &ptr, &len) == -1) {
         Py_DECREF(temp);
         return -1;
     }



More information about the Numpy-svn mailing list