Re: Deterministic destruction and RAII idioms in Python



plahey@xxxxxxxxxxxxxxxxxx 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


.



Relevant Pages

  • Re: beta.python.org content
    ... While it has much in common with them it also has unique features that set it apart. ... "Python is an object oriented programming language designed to increase productivity. ... Though it is often compared to Perl, Tcl, Ruby, Scheme, or Java, it has several powerful features that set it apart." ...
    (comp.lang.python)
  • Re: Deterministic destruction and RAII idioms in Python
    ... >> want (deterministic destruction) ... how that is better than C++-style RAII. ... as you encapsulate more resources. ... I am not criticizing Python or the proposal. ...
    (comp.lang.python)