Python:AND 评估的优化

标签 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 中计算该表达式?

我试图通过谷歌搜索以及在这个网站中找到这个问题的答案

最佳答案

它被称为短路,是的,Python 确实支持它:

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

关于Python:AND 评估的优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54504853/

相关文章:

python - 在pygame中可视化矩阵形成网格

python - 如何使用 SQLAlchemy 关闭并重新连接以避免事务中空闲超时

python - FTP 循环失败连接 Pyth3.6

python - 通过 cron 从 bash 脚本内部运行 python 文件

mysql - 网页数据库查询优化

C++ 调整/优化

python - 在 Python 中,我如何以静态方式一般地引用一个类,比如 PHP 的 "self"关键字?

python - numpy.savetxt 可以用在 N>2 的 N 维 ndarray 上吗?

python - Peewee ORM : Select based on attributes on foreign key fields (backrefs)

javascript - 有没有比 "if-else"链更短的赋值方法?