Deterministic destruction and RAII idioms in Python
noway at sorry.com
Mon Jan 30 23:43:01 CET 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):
for L in f:
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:
f = open(filename)
These building blocks can then be used in the new 'with' statement such as:
with opened("foo.txt") as f:
for L in f:
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.
More information about the Python-list