Surprising difference between StringIO.StringIO and io.StringIO

Cameron Simpson cs at zip.com.au
Thu May 30 19:15:19 EDT 2013


On 30May2013 15:46, Skip Montanaro <skip at pobox.com> wrote:
| Consider this quick session (Python 2.7 using the tip of the 2.7
| branch in Mercurial):
| 
| % python2.7
| Python 2.7.5+ (2.7:93eb15779050, May 30 2013, 15:27:39)
| [GCC 4.4.6 [TWW]] on linux2
[...]
| >>> import io
| >>> s2 = io.StringIO()
[...]
|   File "/home/skipm/x86_64-linux3.1/lib/python2.7/traceback.py", line
| 13, in _print
|     file.write(str+terminator)
| TypeError: unicode argument expected, got 'str'
| >>> print s2.getvalue()
| 
| What is it about io.StringIO that it doesn't like strings and requires
| Unicode?  This is on an OpenSUSE 12.1 system.  I have tried with LANG
| set to the default ("en_US.UTF-8") and to "C".  I also tried on a
| Solaris system with an older micro revision of Python 2.7.  Same
| result.
| 
| Am I missing something about how io.StringIO works?  I thought it was
| a more-or-less drop-in replacement for StringIO.StringIO.

I would expect io.StringIO to be a match for the io.* stuff in Python
3. So it should care whether it is a binary stream or a text stream.
Whereas StringIO.StringIO is your good old Python 2 StringIO, which expects
strs.

On that basis, io.StringIO is a text stream, expecting Unicode
objects for transcription. 'str' is, in that context, probably
considered as 'bytes' in Python 3.

Cheers,
-- 
Cameron Simpson <cs at zip.com.au>

A ship in harbor is safe - but that is not what ships are for.  - John A. Shedd



More information about the Python-list mailing list