[Tutor] Generators
Kent Johnson
kent37 at tds.net
Tue Jul 24 14:11:59 CEST 2007
Tiger12506 wrote:
>> I am new to Python but not new to programming languages. I have seen this
>> "while 1" a lot. In fact in other languages I would expect "while 1" to
>> be
>> the same as "while TRUE".
The predefined constants True and False were not added to Python until
version 2.3. Before that it was common to write 'while 1'.
In fact 'while 1' is more efficient, too. Compare:
In [5]: dis.dis(compile('while 1: pass', '', 'exec'))
1 0 SETUP_LOOP 3 (to 6)
>> 3 JUMP_ABSOLUTE 3
>> 6 LOAD_CONST 0 (None)
9 RETURN_VALUE
In [6]: dis.dis(compile('while True: pass', '', 'exec'))
1 0 SETUP_LOOP 12 (to 15)
>> 3 LOAD_NAME 0 (True)
6 JUMP_IF_FALSE 4 (to 13)
9 POP_TOP
10 JUMP_ABSOLUTE 3
>> 13 POP_TOP
14 POP_BLOCK
>> 15 LOAD_CONST 0 (None)
18 RETURN_VALUE
'while 1' is optimized to just a jump - the compiler recognizes that the
test is not needed and skips it. 'while True' requires looking up the
value of the name 'True' and testing it.
Old habits die hard, especially when they are more efficient and require
less typing :-)
Kent
More information about the Tutor
mailing list