while True or while 1

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Jan 22 00:25:25 EST 2012

On Sun, 22 Jan 2012 09:13:23 +1100, Chris Angelico wrote:

> On Sun, Jan 22, 2012 at 8:13 AM, Erik Max Francis <max at alcyone.com>
> wrote:
>> Why this should concern anyone, I don't know; someone who's rebound
>> `True` or `False` to evaluate to something other than true and false,
>> respectively, is only doing so to be difficult (or very foolish).  One
>> of the principles of Python programming is that We're All Adults Here,
>> so this kind of defensive programming is really superfluous.  In other
>> words, yes, it's quite reasonable to assume that (even in Python 2)
>> `True` is bound to something which is, in fact, true.
> Yes, but there's no special code in the compiler to handle True - it's
> just a name like any other. It finds a token that looks like a name, so
> it puts a name lookup into the bytecode.
>> The real reason people still use the `while 1` construct, I would
>> imagine, is just inertia or habit, rather than a conscious, defensive
>> decision.  If it's the latter, it's a case of being _way_ too
>> defensive.
> Ehh, 'while 1' is shorter too. I reckon some people are just lazy :) 

Or they've been writing Python code since before version 2.2 when True 
and False were introduced, and so they are used to the "while 1" idiom 
and never lost the habit.

In Python 2, "while 1" is a micro-optimization over "while True", because 
there is no need to look-up the name True. For extremely tight loops, 
that may make a difference.

In Python 3, there is no longer any real difference:

py> 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
py> dis(compile('while True: pass', '', 'exec'))
  1           0 SETUP_LOOP               3 (to 6)
        >>    3 JUMP_ABSOLUTE            3
        >>    6 LOAD_CONST               0 (None)
              9 RETURN_VALUE

Or perhaps they just like the look of "while 1".


More information about the Python-list mailing list