Home > Enterprise >  Python - I need a continuous loop that will run forever, I know its bad practice but would using whi
Python - I need a continuous loop that will run forever, I know its bad practice but would using whi

Time:03-31

Would there be any better alternatives to creating a permanent loop (which are not while True) or I'm curious to know if using while True would be fine :) I'm just trying to poll something indefinitely and want to do it all with good coding practice :) Thank you for your time!!

Have just tried while True (which works fine but wondering if theres a better alternative as it doesn't feel right to rely on it)

CodePudding user response:

A little experiment, looking at the bytecode:

>>> import dis
>>> dis.dis('while True: statement')
  1     >>    0 LOAD_NAME                0 (statement)
              2 POP_TOP
              4 JUMP_ABSOLUTE            0 (to 0)

Doesn't even bother checking whether True is true. Just does an unconditional loop. So even the Python compiler recognizes this as something special and treats it as the most optimal thing.

For comparison, using 1 == 1 suggested elsewhere:

>>> dis.dis('while 1 == 1: statement')
  1           0 LOAD_CONST               0 (1)
              2 LOAD_CONST               0 (1)
              4 COMPARE_OP               2 (==)
              6 POP_JUMP_IF_FALSE       12 (to 24)
        >>    8 LOAD_NAME                0 (statement)
             10 POP_TOP
             12 LOAD_CONST               0 (1)
             14 LOAD_CONST               0 (1)
             16 COMPARE_OP               2 (==)
             18 POP_JUMP_IF_TRUE         4 (to 8)
             20 LOAD_CONST               1 (None)
             22 RETURN_VALUE
        >>   24 LOAD_CONST               1 (None)
             26 RETURN_VALUE

Look at all that stuff. Loading the values, comparing them, then testing the comparison result's truth value and jumping around conditionally.

All that said, True isn't the only value optimal in this regard:

>>> dis.dis('while 42: statement')
  1     >>    0 LOAD_NAME                0 (statement)
              2 POP_TOP
              4 JUMP_ABSOLUTE            0 (to 0)
>>> dis.dis('while "foo": statement')
  1     >>    0 LOAD_NAME                0 (statement)
              2 POP_TOP
              4 JUMP_ABSOLUTE            0 (to 0)
>>> 

But I'd say it's additionally the clearest.

CodePudding user response:

The usual and "Pythonic" way to create an infinite loop (assuming you really want one) is indeed while True:. Of course you shouldn't forget to have a break somewhere (that has an actual chance of getting executed).

CodePudding user response:

while True:
    do_something()

That is the best solution.
Alternatively, you can try:

while 1 == 1: #(or "a" == "a", you get it)
    do_something()
  • Related