[Python-ideas] for/else syntax

Steven D'Aprano steve at pearwood.info
Fri Oct 2 16:43:38 CEST 2009


On Fri, 2 Oct 2009 09:06:11 pm Nick Coghlan wrote:

> Just as there is no "try/else", 

Perhaps there should be. Does anyone know why there isn't? It seems an 
arbitrary restriction to me, because the following pieces of code are 
not equivalent:

# not currently legal
try:
    if cond:
        raise ValueError
else:
    print "no exception was raised"
finally:
    print "done"


versus:

try:
    if cond:
        raise ValueError
finally:
    print "done"
print "no exception was raised"



> but only "except/else", so there is 
> no "for/else" or "while/else", but only "break/else".

That's certainly not true.


>>> for x in [1, 2, 3]:
...     pass
... else:
...     print "else without break"
...
else without break


> Issuing a SyntaxWarning might be a good way to make that clear.

Such a warning would be spurious.



-- 
Steven D'Aprano



More information about the Python-ideas mailing list