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

Nick Coghlan ncoghlan at gmail.com
Sat Oct 10 13:42:50 CEST 2009


Steven D'Aprano wrote:
> On Fri, 9 Oct 2009 12:15:10 am Masklinn wrote:
>> 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.
> 
> No entirely -- the compiler generates different byte-code.

I would advise against putting money on that prospect.

>>> def f1():
...   for x in seq:
...     pass
...   else:
...     1
...
>>> def f2():
...   for x in seq:
...     pass
...
...   1
...
>>> from dis import dis
>>> dis(f1)
  2           0 SETUP_LOOP              14 (to 17)
              3 LOAD_GLOBAL              0 (seq)
              6 GET_ITER
        >>    7 FOR_ITER                 6 (to 16)
             10 STORE_FAST               0 (x)

  3          13 JUMP_ABSOLUTE            7
        >>   16 POP_BLOCK

  5     >>   17 LOAD_CONST               0 (None)
             20 RETURN_VALUE
>>> dis(f2)
  2           0 SETUP_LOOP              14 (to 17)
              3 LOAD_GLOBAL              0 (seq)
              6 GET_ITER
        >>    7 FOR_ITER                 6 (to 16)
             10 STORE_FAST               0 (x)

  3          13 JUMP_ABSOLUTE            7
        >>   16 POP_BLOCK

  5     >>   17 LOAD_CONST               0 (None)
             20 RETURN_VALUE

If you leave out the newline after the loop in f2 then the final line
number would change from a 5 to a 4, but the bytecode would otherwise
remain identical. With the extra newline in there, the bytecode *is*
identical.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------



More information about the Python-ideas mailing list