Deterministic destruction and RAII idioms in Python

plahey at alumni.caltech.edu plahey at alumni.caltech.edu
Mon Jan 30 21:55:13 EST 2006


Hi Paul,

>> I looked at pep-0343, it looks interesting.  It is not what I really
>> want (deterministic destruction)
>
>I think it's better.

Is there something specific you have in mind that makes you say that?

I am not a python expert, so I probably do not understand all the
implications of the proposal.  What I got out of it is summarized by:

        with EXPR as VAR:
            BLOCK

    The translation of the above statement is:

        abc = (EXPR).__context__()
        exc = (None, None, None)
        VAR = abc.__enter__()
        try:
            try:
                BLOCK
            except:
                exc = sys.exc_info()
                raise
        finally:
            abc.__exit__(*exc)

Which, looks like you have a constructor (__enter__) and a destructor
(__exit__), which you can always count on being called.  I am not sure
how that is better than C++-style RAII.  Now, in the interest of full
disclosure, there is this __context__ method which I don't really
follow... maybe there is something important there I should know about?

At first glance, it seems to me that the syntax gets slightly ackward
as you encapsulate more resources.  From the proposal:

        with opened(filename, "w") as f:
            with stdout_redirected(f):
                print "Hello world"

which is not as nice as simply creating two objects and having them
destroyed in the reverse order that they were created in when they go
out of scope.  Is it big deal... no.  I am definitely going to have to
play with this stuff a while before I really know its strengths and
weakness relative to C++-style RAII.

If you have some examples, however, to support your feeling that it is
better than C++-style RAII, I would love to see them.  I am always
eager to learn new stuff!

Again, I am not criticizing Python or the proposal.  I like Python and
I like the capabilities that the proposal implies (to the extent that I
understand them :-) ).

As far as PyPy goes, thanks for reminding me of that.  I had forgotten
about that one.

Cheers!




More information about the Python-list mailing list