[Python-ideas] Add a context manager to keep stream position unchanged
Tim Delaney
timothy.c.delaney at gmail.com
Mon Mar 30 00:01:52 CEST 2015
On 30 March 2015 at 04:04, Dmitry Kazakov <jsbfox at gmail.com> wrote:
> I propose adding a context manager to contextlib module, which would
> restore the stream position of its argument at exit:
>
> with contextlib.closing(file_like_object) as file:
> file.read(1)
> old = file.tell()
> with contextlib.keep_stream_position(file) as f:
> assert file is f
> assert file_like_object is f
> # Do something with the file(-like) object e.g. feed it
> # to `PIL.Image.open` (will consume the whole stream)
>
> assert file.tell() == old
>
> This CM would allow us to reuse streams efficiently, without requiring
> to call seek() explicitly. I will open a new issue and submit a patch
> in case of favorable responses.
>
I like the idea. Might need some bikeshedding on the name (maybe
restore_position?).
To test for seeking, I would suggest having a seek to current position
during construction. Not perfect (e.g. there may be streams that can only
seek forwards, not backwards) but I think it's the best non-destructive
option.
Tim Delaney
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150330/9c78af4c/attachment.html>
More information about the Python-ideas
mailing list