Reading a bit too fast, I thought the answer would be in io.stringIO
which allows you to create a file-like object with the content of a string.
But what you want, is an object that, passed to the standard open
function would actually yield a file-like object from the contents of the your string.
The thing is that open
takes a string (or a file descriptor) but anything else will pause a problem.
So I don't believe this way is practical.
But actually, it's not difficult to create a file using tempfile
:
with tempfile.NamedTemporaryFile() as tmp_file:
tmp_file.write(your_string)
yourmodule.YourClass(tmp_file.name)
(If you're on Windows you might want to play with delete=False
and close before sending the name for it to be opened.)
Another approach might be to just change the API: if all the init does with the name is to open a file, why not directly pass a file-like object.