[Python-Dev] Python 2.4 | 7.3 The for statement
Nick Coghlan
ncoghlan at iinet.net.au
Sun Mar 20 04:29:43 CET 2005
Juan Carlos Rodrigo wrote:
>>Interesting idea, but not really needed given the existence of the break statement:
>
>
> Goto = break
> I'm not interested.
All non-sequential control structures are merely constrained ways of using goto
(the underlying machine code will devolve into conditional and unconditional
branches and jumps - i.e. goto's). 'break' is a highly constrained form of goto
and a fundamental part of structured programming (as is 'continue') - each is
limited to a local effect on the loop that contains them. This is a far cry from
the ability to jump to an arbitrary label that gives goto its bad reputation.
I used to share your sentiment regarding break and continue - experience
(especially Python experience) has convinced me otherwise. Python embraces the
concept of breaking out of a loop to the point that it even has an 'else' clause
on loop structures that is executed only if the loop is exited naturally rather
than via a break statement.
Regardless of whether you personally choose to use break and continue, the
existence of those statements is the main reason that the addition of a flag
condition to for loops is highly unlikely. If you want to terminate a for loop
before the iterable is exhausted, the recommended solution is to use a break
statement.
To illustrate the point about all control structures being gotos, even a simple
do-nothing for loop results in a JUMP_ABSOLUTE (goto!) in the generated bytecode:
Py> def f():
... for item in range(10):
... pass
...
Py> import dis
Py> dis.dis(f)
2 0 SETUP_LOOP 20 (to 23)
3 LOAD_GLOBAL 0 (range)
6 LOAD_CONST 1 (10)
9 CALL_FUNCTION 1
12 GET_ITER
>> 13 FOR_ITER 6 (to 22)
16 STORE_FAST 0 (item)
3 19 JUMP_ABSOLUTE 13
>> 22 POP_BLOCK
>> 23 LOAD_CONST 0 (None)
26 RETURN_VALUE
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at email.com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
More information about the Python-Dev
mailing list