Python:AND评估的优化

时间:2019-02-03 16:12:50

标签: python python-3.x optimization evaluation

在Python 3中,我必须检查函数参数中没有出现3个条件,因此,我创建了3个函数:

def check_lenght(string_id):
    # if length is right, return True, otherwise, False

def check_format(string_id):
    # return True if some internal format has to be used, in another case, False

def check_case_num(string_id):
    # manual iteration to check if certain characters are not contained, return True, otherwise, False


def valid_product_code(id_str):
    return check_lenght(id_str) and check_format(id_str) and check_case_num(id_str)

因此,有3个函数,其中一个迭代字符串,此操作可能非常繁重。 但是,如果一个函数已经返回False,则不必检查其余函数,我们知道逻辑AND将返回False,从而可以减少计算量。

因此,我想知道Python(CPython或其他实现)是否正在对此进行优化,因此,return check_lenght(id_str) and check_format(id_str) and check_case_num(id_str)的用法是正确的,还是最好一一检查这些函数并返回False作为更好的选择。他们中的第一个是False时,就会有一个最佳的解决方案,但也许可读性较低。

该表达式如何在Python中求值?

我试图在谷歌上以及在这个网站上找到这个问题的答案

2 个答案:

答案 0 :(得分:2)

它称为short-circuiting,是的,Python确实支持它:

https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not

答案 1 :(得分:2)

a and b and c将不会评估bc,如果a已返回False

x or y将不会评估y,如果x已返回True

您将发现bool运算符几乎可以在所有类似于C的语言中工作。