[Python-Dev] Extended Function syntax
Armin Rigo
arigo@tunes.org
Mon, 3 Feb 2003 17:10:42 +0100
Hello,
On Sun, Feb 02, 2003 at 11:14:41PM +0100, Samuele Pedroni wrote:
> (...do:...)
>
> no there is no first-class thunk here, this is really just sugar for a
> try-finally. The point here is not to need first-class thunks!
If no first-class thunks are wanted, then maybe the most direct path from
today to auto-closing files is to extend the iterator protocol with an
optional __leave__() method. It would be called exactly once when the
iterator is considered to be exhausted. The semantics of 'for' would be
modified to always call it at the end of the loop, even when an exception or a
return occurs within the loop.
It would allow users to write
f = auto_closing_file('data.txt', 'r')
for line in f:
...
or
for lock in synchronized(lock):
...
This second one looks a bit unexpected, but it needs no new syntax and no
brand new protocol. (The 'lock' variable between 'for' and 'in' is not really
needed in this example.)
Armin