python - Python:AND 评估的优化
问题描述
在 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 中评估这个表达式?
我试图在谷歌上搜索这个问题的答案,也在这个网站上
解决方案
它被称为short-circuiting
,是的,Python 确实支持它:
https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not
推荐阅读
- azure - 通过 Azure VM 作为客户端连接到 OpenVPN 服务器
- graphics - 如何在 WebGL 中为 3D 模型绘制刻度尺/标尺
- swift - 如何在编辑模式下删除编辑附件视图和重新排序控件之间的分隔线?
- react-native - FastLane 未能找到联系信息
- magento2 - 如何修复配置magento 2中的js问题?
- android - Microsoft Azure DevOps Pipeline 在 Gradle Android 中因连接重置错误而失败
- c# - EF Core 5 更新未更改的实体和属性
- tableau-api - 两个标志值 0 之间标志值 1 的计数
- c# - 在 ASP .NET Core 的视图数据中返回 Null
- xml - 如何获取xml子节点中值的具体字数?