是True还是1? [英] While True or while 1?
问题描述
我有时在其他人中看到 1,而不是 while True。
我认为使用True更像是pythonic,但我想检查
在实践中是否有任何区别。
I see sometimes in other people code "while 1" instead of "while True". I think using True is more pythonic, but I wanted to check if there is any difference in practice.
所以我尝试了随后,结果令人惊讶。对于
,我可以看到它看起来像解释器可以优化1布尔值
转换,而没有使用True,这与我
的假设相反。
So I tried to do the following, and the result is surprising. For what I can see it looks like the interpreter can optimize away the 1 boolean conversion while it doesn't with the True, the opposite of what I supposed.
任何人都可以解释我为什么会这样,或者我的结论错了吗?
Anyone can explain me why is that, or maybe is my conclusion wrong?
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
推荐答案
编译器无法优化对 True
的引用,因为不幸的是,在python 2中,我可以这样做:
The compiler can't optimize away the reference to True
because, unfortunately, in python 2 I can do this:
True = []
if not True:
print "oops" # :-(
幸运的是,在python 3.2中,我得到 SyntaxError:分配给关键字
。
Luckily, in python 3.2 I get SyntaxError: assignment to keyword
.
这篇关于是True还是1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!