Search code examples
pythonunicodestringio

Unicode problems when using io.StringIO to mock a file


I am using an io.StringIO object to mock a file in a unit-test for a class. The problem is that this class seems expect all strings to be unicode by default, but the builtin str does not return unicode strings:

>>> buffer = io.StringIO()
>>> buffer.write(str((1, 2)))
TypeError: can't write str to text stream

But

>>> buffer.write(str((1, 2)) + u"")
6

works. I assume this is because the concatenation with a unicode string makes the result unicode as well. Is there a more elegant solution to this problem?


Solution

  • The io package provides python3.x compatibility. In python 3, strings are unicode by default.

    Your code works fine with the standard StringIO package,

    >>> from StringIO import StringIO
    >>> StringIO().write(str((1,2)))
    >>>
    

    If you want to do it the python 3 way, use unicode() in stead of str(). You have to be explicit here.

    >>> io.StringIO().write(unicode((1,2)))
    6