[Python-ideas] SyntaxWarning for for/while/else without break or return?
Masklinn
masklinn at masklinn.net
Thu Oct 8 12:16:00 CEST 2009
On 8 Oct 2009, at 11:59 , Stefan Rank wrote:
> on 2009-10-08 11:24 Yuvgoog Greenle said the following:
>> On Thu, Oct 8, 2009 at 10:57 AM, Stefan Rank <list-ener at strank.info
>> <mailto:list-ener at strank.info>> wrote:
>> a suggestion/question related to the discussion about renaming
>> for/else and while/else:
>> Is it easy to generate a SyntaxWarning if you use these constructs
>> without a break or return statement in the loop? AFAICS, any such
>> usage would be either wrong or unnecessary. (right?)
>> Your question is good and valid except that "return" has nothing to
>> do with it.
>> In order to understand the "else" clause it's better that you think
>> of it as an "if not break" after the loop. Any way you look at it
>> "return" behaves as expected - skips the "else" AND skips all the
>> code that follows (much like "raise" would have). "break" is the
>> only way to skip the "else" clause whilst still executing the code
>> that follows the for/while loop.
>> So the only way to the "else" clause is useful is when a "break"
>> can skip it. If there is no "break", you might as well remove the
>> "else" and deindent.
>
> You're right. In the return-but-no-break-example I had in mind::
>
> def findit(bag):
> for elem in bag:
> if isgreat(elem):
> return elem
> else:
> return default
>
> the use of else, though correct and arguably readable, is still
> unnecessary.
So is it in the following cases:
def find_it(bag):
for elem in bag:
if is_great(elem):
raise Whatever(elem)
else:
return default
or
def find_it(bag):
flag = False
for elem in bag:
if is_great(elem):
flag = True
else:
if flag: blow_up()
the point of the SyntaxWarning proposal, as far as I read it, was to
point out that the `else:` clause is only ever useful in the
`for:break else:` case.
So there's no reason to *not* generate a SyntaxWarning if there is a
`return` in the loop if you generate one when there's a `raise`.
More information about the Python-ideas
mailing list