假设我们必须下载一个文件,检查值是否为 True,如果是,我们需要通过电子邮件提醒管理员。
我想将所有不同的事情分成易于管理的步骤(功能)。然后一一调用各个函数。
这将创建以下函数:
def alert_admin():
if download_file() == True: # File is downloaded, check if file is present
if extract_file() == True: # Zip file contains the correct file
if read_file() == True: # Read the file and the value is there
if value_in_file() == True:
# send the admin an email
pass
else:
pass
else:
pass
else:
pass
else:
pass
Run Code Online (Sandbox Code Playgroud)
这感觉不对,有没有更好的方法(更Pythonic)来检查某些函数的结果并继续下一个?
您有几个选项可以避免深度嵌套的控制流。一种流行的方法是“提前返回模式” - 只需测试下一步是否失败,如果失败则立即返回:
def alert_admin():
if not download_file():
return
if not extract_file():
return
if not read_file():
return
if not value_in_file():
return
# send email here
Run Code Online (Sandbox Code Playgroud)
另一种选择是短路。您可以使用布尔运算符链接函数调用and- 如果左侧操作数返回 false,则运算符将跳过计算右侧操作数,从而确保“提前返回”:
def alert_admin():
if download_file() and extract_file() and read_file() and value_in_file():
# send email here
Run Code Online (Sandbox Code Playgroud)
最后,由于函数调用都具有相同的签名,因此您还可以将“步骤”存储在列表中并对其进行迭代 - 这可能会使维护更容易,因为您可以简单地在列表中添加或删除函数名称来更新行为:
def alert_admin():
required_steps = [
download_file
extract_file
read_file
value_in_file
]
for step in required_steps:
if not step():
return
# send email here
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
78 次 |
| 最近记录: |