Pythonic方式结合`for`和`try`块

Que*_*onC 9 python python-3.x

我有解析JSON提要的代码.

对于每个数组,我的代码如下所示:

for node in parse_me:
    # It's important that one iteration failing doesn't cause all iterations to fail.
    try:
        i = node['id'] # KeyError?
        function_that_needs_int (i) # TypeError?
        # possibly other stuff

    except Exception as e:
        LogErrorMessage ('blah blah blah {} in node {}'.fmt(e, node))
Run Code Online (Sandbox Code Playgroud)

我不喜欢这使得我的for循环双嵌套只是因为我需要阻止异常中止循环.有没有办法压扁这段代码?

glg*_*lgl 5

然后你应该做的事情

def iterate_safe(parse_me, message, action):
    for node in parse_me:
        try:
            action(node)
        except Exception as e:
            LogErrorMessage(message.fmt(e, node))
Run Code Online (Sandbox Code Playgroud)

然后把它称为

def action(node):
    do_whatever_must_be_done_with(node)

iterate_safe(parse_me, action, 'blah blah blah {} in node {}')
iterate_safe(parse_me, other_action, 'spam ham {} in node {}')
Run Code Online (Sandbox Code Playgroud)