在OR条件哪一方在python中首先评估?

iam*_*pal 6 python performance

if cpu_expensive_condition() or simple_condition():
        do_something()
Run Code Online (Sandbox Code Playgroud)

在上面的python代码的OR语句中有两个条件,它将首先进行评估?,是否必须对两者进行评估?

Sin*_*ion 16

表达式x or y首先评估x; 如果x为真,则返回其值; 否则,将评估y并返回结果值.

引自Python语言参考


小智 6

Python从左到右求值,两边都不需要求值。考虑以下示例。

def left(x):
    print 'left'
    return x

def right(x):
    print 'right'
    return x

if left(False) or right(False):
    print 'Done'

if left(True) or right(True):
    print 'Done'
Run Code Online (Sandbox Code Playgroud)

这将产生以下输出:

left
right #This is where the first if statement ends.
left
Done  #Only the left side was evaluated
Run Code Online (Sandbox Code Playgroud)