我有一个脚本,它从正在检查不正确数据的记录文件中读入。它们可能各自抛出相同的异常,并且它们存在于同一行。有没有一种方法可以识别哪个字段抛出异常而不必将其分成多行?
此处为玩具示例:
a = [1]
b = [2]
c = [] # Oh no, imagine something happened, like some data entry error
i = 0
try:
z = a[i] + b[i] + c[i]
except IndexError, e:
print "Data is missing! %s" % (str(e))
问题是如果出现异常,用户不知道是a、b还是c有数据丢失。
我想我可以这样写:
def check_data(data, index, message):
try:
return data[index]
except IndexError, e:
print "%s is missing." % (message)
raise e
a = [1]
b = [2]
c = []
i = 0
try:
z = check_data(a, i, "a") + check_data(b, i, "b") + check_data(c, i, "c")
except TypeError, e:
print "Error! We're done."
但这可能非常乏味。
我可以使用哪些其他方法来处理这种情况来验证异常 block 中的每个字段(如果存在)?
下面是根据现实改编的例子:
class Fork:
def __init__(self, index, fork_name, fork_goal, fork_success):
# In reality, we would do stuff here.
pass
forks = []
# In reality, we'd be reading these in and not all of the entries might exist.
fork_names = ["MatrixSpoon", "Spoon", "Spork"]
fork_goals = ["Bend", "Drink soup", "Drink soup but also spear food"]
fork_success = ["Yes!", "Yes!"]
try:
for i in range(0, len(fork_names)):
forks.append(Fork(i + 1, fork_names[i], fork_goals[i], fork_success[i]))
except IndexError, e:
print "There was a problem reading the forks! %s" % (e)
print "The field that is missing is: %s" % ("?")
您可以将错误检查移动到 Fork
类中并使用 itertools.izip_longest
来确保/something/(实际上是 None
)如果一个数据流不足则传入:
class Fork:
def __init__(self, index, fork_name, fork_goal, fork_success):
# first, check parameters
for name, value in (
('fork_name', fork_name),
('fork_goal', fork_goal),
('fork_success', fork_success)
):
if value is None:
raise ValueError('%s not specified' % name)
# rest of code
forks = []
# In reality, we'd be reading these in and not all of the entries might exist.
fork_names = ["MatrixSpoon", "Spoon", "Spork"]
fork_goals = ["Bend", "Drink soup", "Drink soup but also spear food"]
fork_success = ["Yes!", "Yes!"]
然后像这样改变你的循环:
for name, goal, sucess in izip_longest(fork_names, fork_goals, fork_success):
forks.append(Fork(names, goal, success))
现在,您将收到一个错误,清楚地详细说明缺少哪个数据元素。如果您缺少的元素看起来更像 ''
而不是什么都没有,您可以将 __init__
中的测试从 if value is None
更改为 if不是值
。
我是一名优秀的程序员,十分优秀!