且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

“while False"是什么意思?吝啬的?

更新时间:2021-12-01 23:58:44

A whileloop 在每次迭代之前检查 while 后面的条件(好吧,表达式),当条件为 False 时停止执行循环体.

A while loop checks the condition (well, the expression) behind the while before each iteration and stops executing the loop body when the condition is False.

所以 while False 意味着循环体永远不会执行.循环内的一切都是死代码".因此,Python-3.x 会优化"while 循环:

So while False means that the loop body will never execute. Everything inside the loop is "dead code". Python-3.x will go so far that it "optimizes" the while-loop away because of that:

def func():
    i = 1
    while False:
        if i % 5 == 0:
            break
        i = i + 2
    print(i)

import dis

dis.dis(func)

给出以下内容:

  Line        Bytecode

  2           0 LOAD_CONST               1 (1)
              3 STORE_FAST               0 (i)

  7           6 LOAD_GLOBAL              0 (print)
              9 LOAD_FAST                0 (i)
             12 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             15 POP_TOP
             16 LOAD_CONST               0 (None)
             19 RETURN_VALUE

这意味着编译后的函数甚至不知道存在while 循环(第3-6 行没有指令!),因为while 不可能代码>-loop可以被执行.

That means the compiled function won't even know there has been a while loop (no instructions for line 3-6!), because there is no way that the while-loop could be executed.