[Python-ideas] Add a context manager to keep stream position unchanged

Guido van Rossum guido at python.org
Mon Mar 30 03:27:39 CEST 2015


On Sun, Mar 29, 2015 at 10:04 AM, 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 object to the use of the word "efficiently". You save a line of code and
a try/finally block (though the latter probably rarely matters) but the
cost of seeking around in the file (negligible though it is) is not reduced
by using a CM. It also sounds like this would be a really simple exercise,
hardly worth adding to the stdlib.

-- 
--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150329/c4b36556/attachment.html>


More information about the Python-ideas mailing list