[Python-Dev] With statement

Oren Tirosh oren-py-d@hishome.net
Wed, 5 Feb 2003 05:11:18 -0500


On Tue, Feb 04, 2003 at 11:58:15AM -0000, Moore, Paul wrote:
> I'm rapidly tending towards a preference for extreme simplicity in the with
> statement. My basic logic is that the C++ idiom for all this is pretty
> minimal, and works well (even though C++ has no "finally" equivalent, so the
> need is more pressing in C++).
> 
> So, my current feeling is:
> 
>     'with' expr ':'
>         suite
> 
> expands to
> 
>     _x = expr
>     if hasattr(_x, '__enter__'):
>         _x.__enter__()
>     try:
>         suite
>     finally:
> 	if hasattr(_x, '__exit__'):
> 	    _x.__exit__()

Hmmm, __enter__ and __exit__ still look suspiciously like __init__
and __del__ to me. If the problem is that __del__ is not guaranteed to be 
called if there are remaining references to the object (or in a GC based 
system like Jython) why not address this issue directly?

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. The object must have exactly one remaining 
reference, otherwise an exception is raised. In a GC implementation it may 
make some change to the object so that any remaining references to it 
become stale references and raise an exception as soon as they are touched 
in any way. Note that a reference to a closed file object is already a 
stale reference and raises an exception if any I/O operation is attempted 
on it.

So autoclose just becomes:

local f = open(...)

Automatic reference counting and garbage collection is great most of the
time but more explicit control of the intended lifetime of an object can 
sometimes be useful.

	Oren