虽然是真的还是1?

and*_*tti 3 python interpreter bytecode

可能重复:
while(1)Vs. for while(True) - 为什么会有区别?

我有时会在其他人看到代码"while 1"而不是"while True".我认为使用True更加pythonic,但我想检查练习中是否有任何差异.

所以我尝试做以下事情,结果令人惊讶.对于我所看到的,看起来解释器可以优化掉1布尔转换,而不是True,与我想的相反.

任何人都可以解释我为什么会这样,或者说我的结论可能是错的?

def f1():
    while 1:
        pass

def f2():
    while True:
        pass

In [10]: dis.dis(f)
2           0 SETUP_LOOP               3 (to 6)

3     >>    3 JUMP_ABSOLUTE            3
      >>    6 LOAD_CONST               0 (None)
            9 RETURN_VALUE

In [9]: dis.dis(f1)
2           0 SETUP_LOOP              10 (to 13)
      >>    3 LOAD_GLOBAL              0 (True)
            6 POP_JUMP_IF_FALSE       12

3           9 JUMP_ABSOLUTE            3
      >>   12 POP_BLOCK
      >>   13 LOAD_CONST               0 (None)
           16 RETURN_VALUE
Run Code Online (Sandbox Code Playgroud)

sve*_*rre 6

编译器无法优化引用,True因为不幸的是,在python 2中我可以这样做:

True = []
if not True:
    print "oops" # :-(
Run Code Online (Sandbox Code Playgroud)

幸运的是,在python 3.2中我得到了SyntaxError: assignment to keyword.