<div dir="ltr"><div class="gmail_extra"><div class="gmail_quote">On Sun, Mar 29, 2015 at 10:04 AM, Dmitry Kazakov <span dir="ltr"><<a href="mailto:jsbfox@gmail.com" target="_blank">jsbfox@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex">I propose adding a context manager to contextlib module, which would<br>
restore the stream position of its argument at exit:<br>
<br>
with contextlib.closing(file_like_object) as file:<br>
file.read(1)<br>
old = file.tell()<br>
with contextlib.keep_stream_position(file) as f:<br>
assert file is f<br>
assert file_like_object is f<br>
# Do something with the file(-like) object e.g. feed it<br>
# to `PIL.Image.open` (will consume the whole stream)<br>
<br>
assert file.tell() == old<br>
<br>
This CM would allow us to reuse streams efficiently, without requiring<br>
to call seek() explicitly. I will open a new issue and submit a patch<br>
in case of favorable responses.<br></blockquote></div><br>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.<br clear="all"><br>-- <br><div class="gmail_signature">--Guido van Rossum (<a href="http://python.org/~guido">python.org/~guido</a>)</div>
</div></div>