[Python-Dev] With statement
John Williams
jrw@pobox.com
Wed, 05 Feb 2003 11:00:37 -0600
Michael Hudson wrote:
> Oren Tirosh <oren-py-d@hishome.net> writes:
>>Let's assume that a new 'local' statement is added to Python. At the end
>>of the current block the __del__ method of any references declared local
>>is guaranteed to be called. [snip]
>
> Two comments:
>
> 1) The resource-allocation-is-initialization pattern works very well
> in C++, but I'm unconvinced that we should aim to copy it exactly
> -- it's a nice solution to the problem, but not the only possible
> or best one, IMHO.
>
> 2) Without the ability to define a scope at will, RAiI becomes less useful.
Why not combine the "with" and "local" statement ideas? Change the
"with" statement so that there is no __enter__ method, and call __del__
where there current proposal calls __exit__. Now you have
with f = file(...):
# Do something with f.
meaning something similar to
f = file(...)
try:
# Do something with f.
finally:
assert sys.getrefcount(f) == 2
del f
# f is guaranteed dead, so f.__del__ is called