OSDir


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

RFC: Proposal: Deterministic Object Destruction


On Friday, March 2, 2018 at 10:05:41 AM UTC+5:30, 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
> 
> 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: for resources that you care about their 
> *timely* release, 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.

Please excuse if this has been addressed above and/or its too basic:
What's the difference between RAII and python's with/context-managers?