On Friday, March 2, 2018 at 4:35:41 AM UTC, Steven D'Aprano wrote: > On Thu, 01 Mar 2018 16:26:47 -0800, ooomzay wrote: > > >> >> When does the destination file get closed? > >> > > >> > When you execute:- > >> > > >> > del dst > >> > > >> > or:- > >> > > >> > dst = something_else > >> > >> What if you don't? > > > > Then the resource will remain open until your script exits at which > > point it is probably not very well defined exactly when or even if the > > destructor/__del__ will be called. > > > > I.e. Don't do this! Did you have some realistic case in mind or are you > > just probing the behaviour? > > > If you're going to *require* the programmer to explicitly del the > reference: > > f = open("file") > text = f.read() > del f
But I am not! On the contrary RAII frees the programmer from even having to remember to close the file. The poster asked what would happen if the resource was deliberately kept open by storing a reference at global scope. In practice CPython destroys it cleanly on exit - but I am not sure the language guarantees this - in any case RAII won't make things any worse in this respect. (Logfiles are a common example of such global resource.) > then you might as well require them to explicitly close the file: > > f = open("file") > text = f.read() > f.close() > > which we know from many years experience is not satisfactory except for > the simplest scripts that don't need to care about resource management. > That's the fatal flaw in RAII: We must be discussing a different RAII. That is the raison d'etre of RAII: RAII directly addresses this problem in an exception-safe way that does not burden the resource user at all. > the problem is that the lifespan of the resource may > not be the same as the lifetime of the object. > > Especially for files, the > problem is that the lifespan of resource (the time you are actually using > it) may be significantly less than the lifespan of the object holding > onto that resource. Since there's no way for the interpreter to know > whether or not you have finished with the resource, you have a choice: > > - close the resource yourself (either explicitly with file.close(), > or implicitly with a context manager); > > - or keep the resource open indefinitely, until such eventual time > that the object is garbage collected and the resource closed. Hence my PEP! It enables RAII. The interpreter merely has to call __del__ as soon as the object is no longer referenced (as does CPYthon). -- https://mail.python.org/mailman/listinfo/python-list