[Python-ideas] SyntaxWarning for for/while/else without break or return?
jh at improva.dk
Thu Oct 8 16:10:20 CEST 2009
Gerald Britton wrote:
> re warnings: The compiler is simply not smart enough to know if a
> program is doing what a programmer wants. If a given program is
> working quietly according to its specifications, we should do nothing
> to disturb the peace.
If the code is written using a style that is misleading, I think it
makes sense to issue a warning.
> re syntax: There are at least three ways to exit a for-loop early:
> break, return and raise (explicit or implicit). Would this code
> generate a warning? (I hope not)
> for x in y:
> if found_what_I_want(x):
> return True
> return False
This would generate a warning, because the 'else' is unnecessary and
potentially confusing here. The above code is exactly equivalent to:
for x in y:
> or this?
> for a in b:
> if bogus(a):
> raise Bogus, "Found a bad one"
Would also generate a warning. Again, the version without 'else':
for a in b:
raise Bogus, "Found a bad one"
In both cases, I find the version without 'else' to be easier to understand.
+1 to making for/else and while/else without break generate a warning.
+0 to making it an error.
-1 to removing or renaming the 'else' of for and while loops.
More information about the Python-ideas