17

I did this:

import cStringIO.StringIO as StringIO

And I realize I've been using it everywhere. Is that fine? Is it treated the same as StringIO?

TIMEX
  • 259,804
  • 351
  • 777
  • 1,080

2 Answers2

25

They are not the same. cStringIO doesn't correctly handle unicode characters.

>>> StringIO.StringIO().write(u'\u0080')

>>> cStringIO.StringIO().write(u'\u0080')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\x80' in position 0: ordinal not in range(128)
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • @TIMEX: Do you need support for Unicode characters beyond ASCII? – Mark Byers Jan 13 '11 at 06:50
  • No idea. I'm just using StringIO for pictures. and reading pictures , then uploadinng it to S3 – TIMEX Jan 13 '11 at 06:51
  • @Mark Byers - Do you know if cStringIO handles Unicode better in Python3? – Omnifarious Jan 13 '11 at 06:55
  • 5
    @Omnifarious: There's no cStringIO in Python3. It's replaced with io.StringIO and io.BytesIO, which, in line with Python3, are for Unicode and byte strings respectively, and which use native implementations automatically if available (the need to load a native implementation like cStringIO manually in Python2 is most likely a strange API compatibility artifact). – Glenn Maynard Jan 13 '11 at 07:20
  • 6
    On the other hand, if you encode the strings yourself, you can still give them to a cStringIO. For example, `cStringIO.StringIO().write(u'\u2603')` doesn't work, but `cStringIO.StringIO().write(u'\u2603'.encode('utf-8'))` works fine. – rescdsk Aug 03 '12 at 13:13
6

Nor can you set attributes on a cStringIO.StringIO instance:

>>> from cStringIO import StringIO
>>> s = StringIO()
>>> s.name = 'myfile'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'cStringIO.StringO' object has no attribute 'name'

Several libraries depend on File-like objects having either a name or content_type attribute, so cStringIO.StringIO does not work in these instances.

claymation
  • 2,475
  • 4
  • 27
  • 36