Python - 针对关键错误的防御性编程

时间:2014-10-10 13:00:17

标签: python keyerror

我在同一个功能上一直出错,我无法弄清楚原因。我想我第二次修复它,但没有看到为什么这仍然是任何问题。错误会弹出一次,而且会出现。

这是我的第一个错误,但我解决了。

  File "running.py", line 332, in run
TypeError: argument of type 'NoneType' is not iterable ================================================================================
05Oct 03:06:48: Exit status: 1

这是我目前的代码

def get_notifyees(jobdef):
    origNotifyeesList = jobdef['notifyees'] if isinstance(jobdef['notifyees'], list) or jobdef['notifyees'] is None else [jobdef['notifyees']]
    origNotifyeesList = origNotifyeesList if origNotifyeesList is not None else []
    notifyeesList = []
    for notifyee in origNotifyeesList:
        if 'noreply' not in notifyee:
            notifyeesList.append(notifyee)
    return notifyeesList   

但我现在收到此错误

File "running.py", line 337, in get_notifyees
KeyError: 'notifyees'
================================================================================
10Oct 01:53:03: Exit status: 1

1 个答案:

答案 0 :(得分:0)

你有:

origNotifyeesList = jobdef['notifyees'] if isinstance(jobdef['notifyees'], list) or jobdef['notifyees'] is None else [jobdef['notifyees']]

如果KeyError不是notifyees中的关键字,则会引发jobdef。 您可以捕获异常,或者您可以在尝试的地方查看if 'notifyees' in jobdef并使用密钥。