Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's StringIO doesn't do well with `with` statements

I need to stub tempfile and StringIO seemed perfect. Only that all this fails in an omission:

In [1]: from StringIO import StringIO
In [2]: with StringIO("foo") as f: f.read()

--> AttributeError: StringIO instance has no attribute '__exit__'

What's the usual way to provide canned info instead of reading files with nondeterministic content?

like image 313
mike3996 Avatar asked Aug 19 '12 17:08

mike3996


1 Answers

The StringIO module predates the with statement. Since StringIO has been removed in Python 3 anyways, you can just use its replacement, io.BytesIO:

>>> import io
>>> with io.BytesIO(b"foo") as f: f.read()
b'foo'
like image 132
phihag Avatar answered Oct 09 '22 14:10

phihag