python - 调用函数时出现 NameError(寻找更简洁的代码编写方式)
问题描述
我有一个文件,其中包含以 python 变量形式提取的数据。我希望这些数据始终以 2 个变量(检查、输出检查)的形式出现。问题是在某些情况下数据不完整(仅检查变量)或无法提取数据(意味着根本没有变量)。文件的内容将始终根据其提取的数据而有所不同。下面是一个文件示例:
check_1 = "Warning, the check has failed"
output_check_1 = "Here is a more detailed result."
check_2 = "Warning, the check has failed"
#There is no output_check_2 variable
#There is no check_3 at all
接下来,一个函数将根据文件中的数据生成报告:
def create_report(check, output_check):
if check.startswith("Warning"):
print(check)
if output_check:
print(output_check)
else:
print("Sorry, couldn't get a more detailed result")
else:
print("Check was successful.")
#Let's call the function
create_report(check_1, output_check_1) #Works
create_report(check_2, output_check_2) #-> NameError because in this case output_check_2 does not exist
create_report(check_3, output_check_3) #-> NameError because none of the arguments exist
作为修复,我想出了以下内容:
try:
create_report(check_2, output_check_2)
except NameError:
output_check_2 = ""
try:
create_report(check_2, output_check_2)
except NameError:
print("Error - data could not be extracted from the server!")
这样,如果参数 2 (output_check_2) 丢失,我将只收到没有详细数据的检查结果,如果两个参数都丢失(check_3, output_check_3),我将收到一条错误消息,指出无法在全部。
问题是我发现我的“修复”相当野蛮,我正在寻找一种更简洁的方法来获得相同的结果,因为该函数将在执行期间被多次调用。
编辑:变量来自我在脚本开头导入的 extraced_data.py 文件。不幸的是,我无法访问最初生成变量的脚本,因此遇到了这个问题。
解决方案
假设无法修复数据的存储方式*
,您可以使用它getattr
来处理丢失的数据。我假设你正在做这样的事情来导入:
from dataScript import *
将其更改为:
import dataScript
然后你可以这样做:
check1 = getattr(dataScript, "check1", None) # Will default to None if it doesn't exist
if check1 is not None:
create_report(check_1, getattr(dataScript, "output_check1", None))
或者,如果您使用的是 Python 3.8+ 并且check
变量永远不会是空字符串:
if check1 := getattr(dataScript, "check1", None):
create_report(check_1, getattr(dataScript, "output_check1", None))
如果您有任意数量的这些变量,则可能需要使用循环。就像是:
for i in range(MAX_VARS):
n = i + 1
if check := getattr(dataScript, f"check{n}", None):
create_report(check_, getattr(dataScript, f"output_check{n}", None))
MAX_VARS
您期望的最高变量在哪里。
*
这里的输入格式确实是问题所在。使用 Python 脚本作为有时只有正确数据的数据库似乎是真正的问题。我上面的解决方案只是一种解决方法。
推荐阅读
- asp.net - 无法在 Azure 中编辑或删除 .svc。找不到错误 404
- r - 从 R 中的一组局部最大值中获取真正的最大值
- jwt - Keycloak权限信息产品ID
- angular - 将 Spotify 曲目添加到播放列表会返回 401
- reactjs - 在 React 中将 props 传递给组件
- html - 你如何在 Vue 中使用 input type="image"?
- r - r- 使用 sum 和 match 查找高频的第一次出现
- json - 将对象转换为键值对数组
- python - 如何删除通过 pyenv/pip 安装的包
- sas - PROC SGPLOT中curvelabelpos和xaxis的SAS问题