On Fri, 15 Nov 2019 at 22:54, Chris Angelico <rosuav@gmail.com> wrote:
On Sat, Nov 16, 2019 at 9:44 AM Oscar Benjamin <oscar.j.benjamin@gmail.com> wrote:
On Fri, 15 Nov 2019 at 12:04, Serhiy Storchaka <storchaka@gmail.com> wrote:
15.11.19 12:40, Jonathan Fine пише:
The original poster wanted, inside 'with' context management, to open several files. Context management is, roughly speaking, deferred execution wrapped in a try ... except .... statement.
In case of open() there is no deferred execution. The resource is acquired in open(), not in __enter__().
I've often thought that this was the root of various awkwardnesses with context managers. Ideally a well-behaved context manager would only use __exit__ to clean up after __enter__ but open doesn't do that. The nested context manager was designed for this type of well-behaved context manager but was then considered harmful because open (one of the most common context managers) misbehaves.
Maybe some of these things could be simpler if it was clarified that a context manager shouldn't acquire resource before __enter__ and a new version of open was provided.
Hmm. What exactly is the object that you have prior to the file being opened? It can't simply be a File, because you need to specify parameters to the open() call. Is it a "file ready to be opened"? What's the identity of that?
Good question :) Maybe it's an "opener": class opener: def __init__(self, *args): self.args = args def __enter__(self): fileobj = self.fileobj = open(*self.args) return self.fileobj def __exit__(self, *args): return self.fileobj with opener('w.txt', 'w') as fout: fout.write('asd\n'*10) -- Oscar