[Python-ideas] SyntaxWarning for for/while/else without break or return?

Gerald Britton gerald.britton at gmail.com
Thu Oct 8 15:44:40 CEST 2009

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.

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

or this?

for a in b:
  if bogus(a):
     raise Bogus, "Found a bad one"

On Thu, Oct 8, 2009 at 9:15 AM, Masklinn <masklinn at masklinn.net> wrote:
> On 8 Oct 2009, at 15:08 , Gerald Britton wrote:
>> I'm still pretty much against the whole idea of changing this syntax
>> or issuing warnings.  I like writing:
>> # for loop using else clause
>> for x in y:
>>  do_something_with(x)
>>  if something_happened_with(x):
>>    break
>> else: # only get here if nothing happened
>>  nothing_happened()
>> #end of for loop
> [snip]
>> if a warning were issued instead,
>> working programs would suddenly spout spurious messages.
> None of the proposals (as far as I can see) would emit a warning on this
> snippet: there is a `break` going with the `else:` clause, which is (as far
> as I can say from the discussion) the normal use case for `for: else:`.
> The SyntaxWarning proposed would only be emitted on a `for: else:` *without*
> a break as it's entirely equivalent to just deleting the `else:` clause and
> dedenting the code it contains.
> As far as outputting "spurious" messages in working programs, that's the
> point of a warning isn't it? Tell the programmer that something works, but
> might not do what one would like (or does nothing at all).

Gerald Britton

More information about the Python-ideas mailing list