[Python-Dev] Re: anonymous blocks

Greg Ewing greg.ewing at canterbury.ac.nz
Tue Apr 26 14:58:41 CEST 2005


Guido van Rossum wrote:
> [Greg Ewing]
>>* It seems to me that this same exception-handling mechanism
>>would be just as useful in a regular for-loop, and that, once
>>it becomes possible to put 'yield' in a try-statement, people
>>are going to *expect* it to work in for-loops as well.
> 
> (You can already put a yield inside a try-except, just not inside a
> try-finally.)

Well, my point still stands. People are going to write
try-finally around their yields and expect the natural
thing to happen when their generator is used in a
for-loop.

> There would still be the difference that a for-loop invokes iter() and
> a with-block doesn't.
 >
 > Also, for-loops that don't exhaust the iterator leave it available for
 > later use.

Hmmm. But are these big enough differences to justify
having a whole new control structure? Whither TOOWTDI?

>     """
>     The statement:
> 
>         for VAR in EXPR:
>             BLOCK
> 
>     does the same thing as:
> 
>         with iter(EXPR) as VAR:        # Note the iter() call
>             BLOCK
> 
>     except that:
> 
>     - you can leave out the "as VAR" part from the with-statement;
>     - they work differently when an exception happens inside BLOCK;
>     - break and continue don't always work the same way.
> 
>     The only time you should write a with-statement is when the
>     documentation for the function you are calling says you should.
>     """

Surely you jest. Any newbie reading this is going to think
he hasn't a hope in hell of ever understanding what is going
on here, and give up on Python in disgust.


>>I'm seriously worried by the
>>possibility that a return statement could do something other
>>than return from the function it's written in.

> Let me explain the use cases that led me to throwing that in

Yes, I can see that it's going to be necessary to treat
return as an exception, and accept the possibility that
it will be abused. I'd still much prefer people refrain
from abusing it that way, though. Using "return" to spell
"send value back to yield statement" would be extremely
obfuscatory.

> (BTW ReturnFlow etc. aren't great
> names.  Suggestions?)

I'd suggest just calling them Break, Continue and Return.

>     synchronized(lock):
>         BLOCK
> 
>     transactional(db):
>         BLOCK
> 
>     forever():
>         BLOCK
> 
>     opening(filename) as f:
>         BLOCK

Hey, I like that last one! Well done!

> One last thing: if we need a special name for iterators and generators
> designed for use in a with-statement, how about calling them
> with-iterators and with-generators.

Except that if it's no longer a "with" statement, this
doesn't make so much sense...

Greg







More information about the Python-Dev mailing list