[Python-Dev] cStringIO.StringIO() buffer behavior

Alexandre Vassalotti alexandre at peadrop.com
Mon Aug 6 21:43:23 CEST 2007


On 8/6/07, Georg Brandl <g.brandl at gmx.net> wrote:
> Okay, I propose the following patch:
> [...]

I think your patch is complicated for nothing. It would be much more
straightforward to use PyString_AsStringAndSize to encode the Unicode
string with the default encoding. I think it would be necessary to
port the fix to O_write and O_writelines.

-- Alexandre

Index: Modules/cStringIO.c
===================================================================
--- Modules/cStringIO.c (revision 56754)
+++ Modules/cStringIO.c (working copy)
@@ -665,8 +674,15 @@
   char *buf;
   Py_ssize_t size;

-  if (PyObject_AsCharBuffer(s, (const char **)&buf, &size) != 0)
-      return NULL;
+  /* Special case for unicode objects. */
+  if (PyUnicode_Check(s)) {
+         if (PyString_AsStringAndSize(s, &buf, &size) == -1)
+                 return NULL;
+  }
+  else {
+         if (PyObject_AsReadBuffer(s, (const void **)&buf, &size) == -1)
+                 return NULL;
+  }

   self = PyObject_New(Iobject, &Itype);
   if (!self) return NULL;


More information about the Python-Dev mailing list