On Sat, Nov 16, 2019 at 10:21 AM Andrew Barnert
On Nov 15, 2019, at 14:52, Chris Angelico
wrote: On Sat, Nov 16, 2019 at 9:44 AM Oscar Benjamin
wrote: On Fri, 15 Nov 2019 at 12:04, Serhiy Storchaka
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?
The notion of a “file ready to be opened” makes some sense. I’d expect such a thing to have methods like “read_contents”, “write_contents” (plus maybe atomic write, append, etc. variants) that you often use, and you only use it as a context manager if you want to get an iterable of lines out of it or something else you can access iteratively rather than all at once.
If __enter__ is the place where all resources are allocated, then the constructor has to record file name (and dirfd), whether to open for reading or writing, the encoding/errors, and everything else you need to know before you can open it. Basically it'd have to record all the arguments to open(), plus any additional state required (current directory, perhaps) in case it can change. The "file ready to be opened" would have to actually be "this file, to be read from in UTF-8 mode and not written to". I think it'd be at least as confusing as the current situation. ChrisA