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

Andrew Barnert abarnert at yahoo.com
Mon Mar 30 02:40:36 CEST 2015


On Mar 29, 2015, at 10: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'm pretty sure an implementation of this is already on PyPI somewhere, although I can't remember exactly where, and it's possible that I just built it myself when needed rather than finding it... 

Anyway, if I'm right, that would be helpful for both bikeshedding the name, and spotting any potential problems that had to be worked around (the need for f.seek(f.tell()) to catch non-seekable files early is the only non-obvious one I can think of, but if someone has been using this for years in a wide range of projects, they may have found one that none of us will immediately think of).


> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/


More information about the Python-ideas mailing list