On Mon, 18 Nov 2019 at 17:17, Oscar Benjamin <oscar.j.benja...@gmail.com> wrote:
> The problem with a misbehaving context manager is that it creates a
> future need to call __exit__ before it has been passed to a with
> statement or any other construct that can guarantee to do that.

You seem to be focusing purely on the usage

    with open(filename) as f:
        # use f

But open() isn't designed *just* to be used in a with statement. It
can be used independently as well. What about

    f = open(filename)
    header = f.readline()
    with f:
        # use f

The open doesn't "create a future need to call __exit__". It *does*
require that the returned object gets closed at some stage, but you
can do that manually (for example, if "header" in the above is "do not
process", maybe you'd close and return early). The context manager
behaviour of a file object lets you use a with statement to say "when
this block completes, make sure the file is closed", but it does *not*
require you to do so.

You can wrap open() in a context manager like opened() that *does*
work like that, but it's not the only way to write context managers.
Certainly, nested() can't be written to safely work with the full
generality of context managers as we currently have them, but as I
said that's a trade-off.

Maybe I should ask the question the other way round. If we had
opened(), but not open(), how would you write open() using opened()?
It is, after all, easy enough to write opened() in terms of open().

Anyway, I already said that where you choose to draw the line over
what a context manager is (assuming you feel that the current
definition is wrong), depends on your perspective. So I'm not trying
to persuade you that I'm right over this. Unless this turns into a PEP
to change the language (and I think it would need a PEP) it's just
speculation and collecting opinions, so you have mine ;-)

Paul
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/KPYEEZQ63DNWTJAGWNPB4GE5KOYVCZW2/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to