RAII vs gc (was fortran lib which provide python like data type)

Devin Jeanpierre jeanpierreda at gmail.com
Sat Jan 31 22:27:22 EST 2015


On Fri, Jan 30, 2015 at 1:28 PM, Sturla Molden <sturla.molden at gmail.com> wrote:
> in Python. It actually corresponds to
>
> with Foo() as bar:
>     <suite>

The problem with with statements is that they only handle the case of
RAII with stack allocated variables, and can't handle transfer of
ownership cleanly.

Consider the case of a function that opens a file and returns it:

def myfunction(name, stuff):
    f = open(name)
    f.seek(stuff) # or whatever
    return f

def blahblah():
    with myfunction('hello', 12) as f:
         ....

This code is wrong, because if an error occurs during seek in
myfunction, the file is leaked.

The correct myfunction is as follows:

def myfunction(name, stuff)
    f = open(name)
    try:
        f.seek(stuff)
    except:
        f.close()
        raise

Or whatever. (I would love a close_on_error context manager, BTW.)

With RAII, the equivalent C++ looks nearly exactly like the original
(bad) Python approach, except it uses unique_ptr to store the file,
and isn't broken. ("Modern") C++ makes this easy to get right. But
then, this isn't the common case.

-- Devin



More information about the Python-list mailing list