Deterministic destruction and RAII idioms in Python

Giovanni Bajo noway at sorry.com
Mon Jan 30 17:43:01 EST 2006


plahey at alumni.caltech.edu wrote:

> Giving up deterministic destruction in Python would be a real blow for
> me, since it is one of its unique features among GC'ed languages.
>
> So what's the deal, can I rely on it in "mainstream" Python or am
> I out of luck here?


Most people rely on that. I do that *all* the time, and I would really dislike
if CPython lose this feature. Anyway, if you want to make your code portable to
other Python implementations, you'll have to implement your RAII idioms in a
slightly different way. Specifically, Python supports a try/finally construct
that it is useful to properly release resources. Eg. the following code is
"correct" even with IronPython:

f = file(name):
try:
  for L in f:
    print L
finally:
  f.close()

Anyway, there is some work being done to add some RAII constructs to the
language that are compatibile across Python implementations. See the new "with"
statement. http://www.python.org/peps/pep-0343.html. This would allow to write
generic "functors" for RAII using generators, such as:

@contextmanager
def opened(filename):
    f = open(filename)
    try:
        yield f
    finally:
        f.close()

These building blocks can then be used in the new 'with' statement such as:

   with opened("foo.txt") as f:
         for L in f:
             print L

Of course, there's more to this (eg, 'with' statement can be used also with
normal objects as long as they support new __enter__ and __exit__ special
method), so go to the link above for more details and more juicy examples that
I'm sure you'll like.
-- 
Giovanni Bajo





More information about the Python-list mailing list