Incuriosito da questa domanda sui loop infiniti in perl: while (1) Vs. per (;;) C'è una differenza di velocità? , Ho deciso di eseguire un confronto simile in Python. Mi aspettavo che il compilatore generasse lo stesso byte code per while(True): passe while(1): pass, ma in realtà non è così in python2.7.
Il seguente script:
import dis
def while_one():
while 1:
pass
def while_true():
while True:
pass
print("while 1")
print("----------------------------")
dis.dis(while_one)
print("while True")
print("----------------------------")
dis.dis(while_true)
produce i seguenti risultati:
while 1
----------------------------
4 0 SETUP_LOOP 3 (to 6)
5 >> 3 JUMP_ABSOLUTE 3
>> 6 LOAD_CONST 0 (None)
9 RETURN_VALUE
while True
----------------------------
8 0 SETUP_LOOP 12 (to 15)
>> 3 LOAD_GLOBAL 0 (True)
6 JUMP_IF_FALSE 4 (to 13)
9 POP_TOP
9 10 JUMP_ABSOLUTE 3
>> 13 POP_TOP
14 POP_BLOCK
>> 15 LOAD_CONST 0 (None)
18 RETURN_VALUE
L'utilizzo while Trueè notevolmente più complicato. Perchè è questo?
In altri contesti, python si comporta come se fosse Trueuguale a 1:
>>> True == 1
True
>>> True + True
2
Perché whiledistingue i due?
Ho notato che python3 valuta le istruzioni utilizzando operazioni identiche:
while 1
----------------------------
4 0 SETUP_LOOP 3 (to 6)
5 >> 3 JUMP_ABSOLUTE 3
>> 6 LOAD_CONST 0 (None)
9 RETURN_VALUE
while True
----------------------------
8 0 SETUP_LOOP 3 (to 6)
9 >> 3 JUMP_ABSOLUTE 3
>> 6 LOAD_CONST 0 (None)
9 RETURN_VALUE
C'è un cambiamento in python3 nel modo in cui vengono valutati i booleani?