I have a function that takes an opened file object file and writes data to it like so:
def Write(self, file):
file.write("Data")
Now I would like to test that function and I thought it would be neat to do that with some kind of stream that is not writing data to a file. I could not find a Python2.7 class that does the job except the StringIO class. However, in Python2.7 this class expects a unicode string in the write function. (file.write(u"Data")) So I cannot test my Write function with the StringIO class.
In my workaround I created a little dummy class
class MyStream(object):
S = property(lambda self: self._S)
def __init__(self):
self._S = ""
def write(self, s):
self._S += s
with which I can now successfully test my Write function.
My question:
Is there a native python class that does the same trick?
Thx in advance for any suggestions
Regards Woltan
As the documentation of
iostates:I.e. if you use the backported Python 3 IO library, you have to use unicode. However, the original
StringIOclass – which considers bytes (Python 2 strings) text and accepts them – still exists in Python 2.7, it’s just not in the backportedio. Instead, it has its own module, also calledStringIO.