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