[Python-Dev] Acquire/release functionality

Moore, Paul Paul.Moore@atosorigin.com
Mon, 3 Feb 2003 14:31:39 -0000


Paul Moore <lists@morpheus.demon.co.uk> writes:

> As far as the acquire/release case is concerned, I think that there is
> definitely a strong case for syntactic support for this. The
> equivalent idiom in C++ is "resource acquisition is initialisation"
> which, while not having syntax support, does rely on the existence of
> deterministic destructors, and on the ability to introduce a new scope
> at will. Python has neither of these, and the try...finally construct
> is verbose enough to make something better worth having.

In trying to draw a parallel between "with" and the C++ RAII idiom, I
hit a funny, best illustrated by an example:

    class autoclose(file):
        __exit__ =3D close

    with f =3D autoclose("blah.txt", "r"):
        # Let's get sneaky
        g =3D f
        # Main code here

    # File now gets closed
    with g:
       # Who's a naughty boy then - g is a closed file
    # And the g.__exit__() call goes boom here...

OK, it's contrived. The equivalent C++ risk is that of creating a =
dangling
pointer to a local variable which is deleted, which is also rare.

I don't know if this is a significant issue - after all, I can write
code which closes a closed file object in normal Python. But I do think
that we should remember the weird edge cases when discussing this sort
of thing.

If nothing else, it strikes me as a mild argument in favour of allowing
the assignment to be part of the "with" clause, just so that people
don't get used to seeing a bare "with g" (which doesn't include any
obvious clues that g *needs* auto-cleanup).

Paul.