1

我有这么长的 try except 声明列表:

    try:
       uri = entry_obj['media$group']['media$content'][0]['url']
    except (KeyError, IndexError):
       uri = None
    try:
       position = entry_obj['yt$position']['$t']
    except KeyError:
       position = None
    try:
       description = entry_obj['content']['$t']
    except KeyError:
       description = None
    try:
       seconds = entry_obj['media$group']['yt$duration']['seconds']
    except KeyError:
       seconds = None
    try:
       thumbnails = entry_obj['media$group']['media$thumbnail']
    except KeyError:
       thumbnails = None

有没有更简洁的方法来写这个?

4

3 回答 3

9

如果您厌倦了弄清楚在get()调用中使用什么作为默认值,只需编写一个辅助函数:

def resolve(root, *keys):
   for key in keys:
       try:
           root = root[key]
       except (KeyError, IndexError):
           return None
   return root

然后你就写,例如:

uri = resolve(entry_obj, 'media$group', 'media$content', 0, 'url')

为了稍微简化调用,您可能会增强辅助函数以将单个字符串作为键并在空格上拆分;这样你就不必输入那么多引号,我们还可以添加一个默认值参数:

def resolve(root, keys, default=None):
    for key in keys.split():
        try:
            root = root[key]
        except (TypeError, KeyError):
            try:
                root = root[int(key)]
            except (IndexError, ValueError, KeyError):
                return default

uri = resolve(entry_obj, 'media$group media$content 0 url', '')
于 2012-06-07T04:42:27.817 回答
2

我想到了另一种好方法来做到这一点,不知道它与 kindall 的方法相比如何。我们首先定义一个方法属性:

def res(self, property):
    try:
        return property()
    except (KeyError, IndexError):
        return None

然后将 try-except 语句替换为:

    url = res(lambda: entry_obj['media$group']['media$content'][0]['url'])
    position = res(lambda: entry_obj['yt$position']['$t'])
    description = res(lambda: entry_obj['content']['$t'])
    duration = res(lambda: entry_obj['media$group']['yt$duration']['seconds'])
    thumbnails = res(lambda: entry_obj['media$group']['media$thumbnail'])
于 2012-06-10T02:09:58.543 回答
1

改用get字典的方法:

position = entry_object.get('yt$position').get('$t')

get将处理您不存在的键的情况,并在这种情况下为您提供(可更改的)后备值。您仍然需要IndexError手动处理第一个,但所有这些except KeyError:都会消失。

于 2012-06-07T04:31:36.300 回答