while (1) vs. while(True) -- Why is there a difference (in python 2 bytecode)?
Solution 1:
In Python 2.x, True
is not a keyword, but just a built-in global constant that is defined to 1 in the bool
type. Therefore the interpreter still has to load the contents of True
. In other words, True
is reassignable:
Python 2.7 (r27:82508, Jul 3 2010, 21:12:11)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> True = 4
>>> True
4
In Python 3.x it truly becomes a keyword and a real constant:
Python 3.1.2 (r312:79147, Jul 19 2010, 21:03:37)
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> True = 4
File "<stdin>", line 1
SyntaxError: assignment to keyword
thus the interpreter can replace the while True:
loop with an infinite loop.
Solution 2:
It isn't quite right, to call it an "infinite loop"
thus the interpreter can replace the while True: loop with an infinite loop.
because one can still break out of such a while True:
loop. But such a loop's else
clause would never be accessed in Python 3.
And Python 3's simplifying of the value lookup for True
makes it run just as quickly as while 1
in Python 2.
Performance Comparison
Demonstrating the difference in time for a somewhat nontrivial while loop:
Setup
def while1():
x = 0
while 1:
x += 1
if x == 10:
break
def whileTrue():
x = 0
while True:
x += 1
if x == 10:
break
Python 2
>>> import timeit
>>> min(timeit.repeat(while1))
0.49712109565734863
>>> min(timeit.repeat(whileTrue))
0.756627082824707
Python 3
>>> import timeit
>>> min(timeit.repeat(while1))
0.6462970309949014
>>> min(timeit.repeat(whileTrue))
0.6450748789939098
Explanation
To explain the difference, in Python 2:
>>> import keyword
>>> 'True' in keyword.kwlist
False
but in Python 3:
>>> import keyword
>>> 'True' in keyword.kwlist
True
>>> True = 'true?'
File "<stdin>", line 1
SyntaxError: can't assign to keyword
Since True
is a keyword in Python 3, the interpreter doesn't have to look up the value to see if someone replaced it with some other value. But since one can assign True
to another value in Python 2, the interpreter has to look it up every time.
Conclusion for Python 2
If you have a tight, long-running loop in Python 2, you probably should use while 1:
instead of while True:
.
Conclusion for Python 3
Use while True:
if you have no condition for breaking out of your loop.