On Tue, Nov 19, 2019 at 5:47 AM Andrew Barnert via Python-ideas <python-ideas@python.org> wrote:
Unless there’s some case where you don’t want to close f at all, I don’t see why you don’t want a context manager. For example, your return early case:
with open(filename) as f: header = f.readline() if something(header): return # use f
… does exactly what you wanted, and also properly handles exceptions. Which is the whole point of context managers.
I suppose if you wanted to close f in some different way in some situations… but there is no different way to close files.
There is one other common way you might want to close a file, and that's "close it if I opened it, but otherwise don't". For example, if you're given a file name to output into, then write to that file; but otherwise, write to sys.stdout. I'm not sure what the best way to do that is, other than ExitStack, which feels clunky (like using a while loop to emulate a for loop - sure it works, but it feels wrong). ChrisA