我有一个最小的工作示例代码:
test.py :
a = 4
b = 6
l = [4, 6, 7, 8]
for t in l :
if t == a or t == b:
continue
print(t)
我正在使用
pdb
(python-3.9.2
) 单步执行代码:
local: ~ $ python -m pdb test.py
> test.py(1)<module>()
-> a = 4
(Pdb) b 5
Breakpoint 1 at test.py:5
(Pdb) c
> test.py(5)<module>()
-> if t == a or t == b:
(Pdb) p t,a
(4, 4)
(Pdb) p t == a
True
(Pdb) t == a or t == b
True
(Pdb) n #### <<--- Conditional is True, why doesn't it explicitly step into it?
> test.py(4)<module>()
-> for t in l :
(Pdb) n
> test.py(5)<module>()
-> if t == a or t == b:
(Pdb) p t==a, t==b
(False, True)
(Pdb) t == a or t == b
True
(Pdb) n #### <<--- Conditional is True, and it explicitly steps into it
> test.py(6)<module>()
-> continue
(Pdb) t == a or t == b
True
问题:
pdb
在t==b
而不是t==a
时显式进入条件?这是优化吗?我认为这是由于操作员短路造成的。
给出这个表达式:
if cond1 or cond2:
如果 cond1 为真,那么我们就有了答案。
cond2
是什么并不重要——表达式 作为一个整体 保证为真。所以 Python 甚至不会去计算 cond2
.
类似地:
if cond1 and cond2:
如果 cond1 为假,那么我们又得到了答案。
cond2
是什么并不重要——表达式 作为一个整体 肯定是假的。所以 Python 不会费心去评估cond2
.