RFC: Proposal: Deterministic Object Destruction

Gregory Ewing greg.ewing at canterbury.ac.nz
Sat Mar 3 20:57:44 EST 2018


ooomzay at gmail.com wrote:
> Well he was not telling you the whole story: RAII works just as well with
> heap objects using smart pointers (unique_ptr and friends) which are a closer
> analogy to python object references.

By that definition, *all* resource management in Python is
based on RAII[1]. The only difference is that in Python the
only way to destroy an object is to remove all references to
it, whereas in C++ you have some other options (explicit
delete, stack allocation, etc.)

However, when people talk about RAII in C++ they're
*usually* referring to stack-allocated objects. There are
various ways of getting the same effect in Python:

(a) Rely on CPython reference counting

(b) Use a with-statement

(c) Use a try-finally statement

Of these, (a) is the closest in spirit to stack-allocated
RAII in C++, but it's only guaranteed to work in current
CPython.

[1] Well, not quite -- you can use low-level OS calls to
open files, etc. But the high-level wrappers for files,
sockets, and so forth all use RAII.

-- 
Greg



More information about the Python-list mailing list