On 2019-11-18 5:13 p.m., Andrew Barnert via Python-ideas wrote:
On Nov 18, 2019, at 10:51, Random832 email@example.com wrote:
On Mon, Nov 18, 2019, at 12:46, Paul Moore wrote:
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).
sure, but "need to call close" is just a different spelling of "need to call __exit__".
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().
I would say open() is arguably a wart. Had context managers existed in the language all along, it should not be possible to do anything that creates an open-ended future requirement to do something (i.e. "require that the returned object gets closed at some stage") without either using a with statement or writing code to manually call __enter__ and __exit__. The likely most common case being a class that holds an open file, which should really have its own context manager that forwards to the file's.
to that end, open() could look something like this:
def open(*a,**k): cm = opened(*a, **k) f = cm.__enter__() f.close = cm.__exit__ return f
I think in that hypothetical language you might want a generic “releaser” function, or method on all cms, or even special syntax, to turn any cm into something that you’ll take care of closing later manually (usually, but not necessarily, by using the closing cm on it in a different lexical context that you end up passing the released cm to).
(I think C++ smart pointers might be relevant here, or maybe something from Rust, although I haven’t thought it through in much detail.)
could we tweak open() so it doesn't raise immediately? this would make it play nicer with __enter__ but would probably break some things. this would make open() itself "never" fail.
Python-ideas mailing list -- firstname.lastname@example.org To unsubscribe send an email to email@example.com https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://firstname.lastname@example.org/message/7Y4B5G... Code of Conduct: http://python.org/psf/codeofconduct/