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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With