progo progo - 1 year ago 68
Python Question

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

I need to stub

seemed perfect. Only that all this fails in an omission:

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

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

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

Answer Source

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: