RFC: Proposal: Deterministic Object Destruction

Chris Angelico rosuav at gmail.com
Wed Feb 28 19:19:18 EST 2018


On Thu, Mar 1, 2018 at 10:48 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> On Wed, 28 Feb 2018 14:51:09 -0800, ooomzay wrote:
>> Motivation
>> ==========
>>
>> To make the elegance (simplicity, generality, and robustness) of the
>> "Resource Acquisition Is Initialization" (RAII) idiom available to all
>> python applications and libraries.
>
> I've never yet seen an explanation of RAII that makes the least amount of
> sense. I wouldn't call it either elegant or simple. More like "confusing
> and badly named".

Badly named, yes, but it's not too confusing. RAII is just a fancy
name for "when I construct a file object, you open the file, and when
the file object is disposed of, you close the file for me". Which is
exactly how Python works, with the exception that RAII depends on
prompt object disposal (hence the OP's demands). In CPython, you can
happily write this:

def save_file(fn):
    f = open(fn, "w")
    print(data, file=f)
    print(more_data, file=f)

save_file(...)

The file object gets disposed of as the function terminates, and the
underlying file handle gets closed. That's RAII. The only problem is
that this doesn't work reliably with reference counting (the C++ way
to do it is to have a single automatic object, no refcounting, no
pointers, nothing), and definitely doesn't work with most non-refcount
garbage collection (mark-and-sweep, arena, etc).

>> Backwards Compatibility
>> =======================
>>
>> This proposal preserves 100% backwards compatibility.
>
> So long as you're not using IronPython, Jython, or some alternate builds
> of PyPy.
>

Hmm, I think actually it does; if all Python implementations magically
became compliant with the OP's demands, they'd be fully
backward-compatible. This is a tightening of requirements on the
language.

It's still not a good idea though. :)

ChrisA



More information about the Python-list mailing list