[Python-Dev] anonymous blocks
Shane Hathaway
shane at hathawaymix.org
Fri Apr 22 19:11:25 CEST 2005
Nick Coghlan wrote:
> An alternative would be to replace the 'yield None' with a 'break' or
> 'continue', and create an object which supports the resource protocol
> and NOT the iterator protocol. Something like:
>
> def my_resource():
> print "Hi!" # Do entrance code
> continue # Go on with the contents of the 'with' block
> print "Bye!" # Do exit code
>
> (This is currently a SyntaxError, so it isn't ambiguous in any way)
That's a very interesting suggestion. I've been lurking, thinking about
a way to use something like PEP 310 to help manage database
transactions. Here is some typical code that changes something under
transaction control:
begin_transaction()
try:
changestuff()
changemorestuff()
except:
abort_transaction()
raise
else:
commit_transaction()
There's a lot of boilerplate code there. Using your suggestion, I could
write that something like this:
def transaction():
begin_transaction()
try:
continue
except:
abort_transaction()
raise
else:
commit_transaction()
with transaction():
changestuff()
changemorestuff()
Shane
More information about the Python-Dev
mailing list