RFC: Proposal: Deterministic Object Destruction
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Fri Mar 2 17:41:13 EST 2018
On Fri, 02 Mar 2018 07:09:19 -0800, ooomzay wrote:
[...]
>> 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.
You say that as if it were difficult to do, requiring the programmer to
take extraordinary steps of heroic proportion. It doesn't.
It is unbelievably easy to store the reference at global scope, which
means that the programmer needs to remember to close the file explicitly
and RAII doesn't help.
> In practice CPython destroys it cleanly on exit - but I am not sure the
> language guarantees this
Typically the OS guarantees that any open files will be closed when the
application exits. But that *absolutely does not* apply to other
resources that may need closing, and Python at least doesn't guarantee to
run __del__ during application shutdown as it may not be able to.
(It is better now than it used to be, but there are still scenarios where
the resources needed to run __del__ are gone before __del__ is called.)
> - in any case RAII won't make things any worse
> in this respect. (Logfiles are a common example of such global
> resource.)
I didn't say RAII will make it worse, but neither will it make it better,
nor make "with" statements obsolete.
Your justification for requiring RAII is to ensure the timely closure of
resources -- but to do that, you have to explicitly close or delete the
resource. It simply isn't true that "RAII frees the programmer from even
having to remember to close the file".
>> 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.
But as you said yourself, if the resource is held open in a global
reference, it will stay open indefinitely. And remember, global in this
context doesn't just mean the main module of your application, but
*every* module you import.
I think you have just put your finger on the difference between what RAII
*claims* to do and what it *actually* can do.
--
Steve
More information about the Python-list
mailing list