简体   繁体   English

简洁地替换Python中的Try-Except语句的长列表?

[英]Concise replacement for long list of Try-Except statement in Python?

I have this long list of try except statement: 我有很多尝试,除了声明:

    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

Is there a more concise way to write this? 有没有更简洁的方式来编写此代码?

If you tire of figuring out what to use for default values in get() calls, just write a helper function: 如果您厌烦了要在get()调用中使用什么作为默认值,只需编写一个辅助函数:

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

Then you just write, eg: 然后,您只需编写,例如:

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

To simplify the calls a little, you might beef up the helper function to take a single string for the keys and split on spaces; 为了稍微简化调用,您可以增强助手功能,以单个字符串作为键并在空格处分割; that way you don't have to type so many quotes, and we can also add a default value argument: 这样,您不必输入太多引号,我们还可以添加默认值参数:

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', '')

I thought of another good way to do this, not sure how it compares to kindall's method. 我想到了另一种好的方法,不确定如何与kindall的方法进行比较。 We first define a method property: 我们首先定义一个方法属性:

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

Then replace the try-except statements with: 然后将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'])

Use the get method of dictionaries instead: 改用字典的get方法:

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

get will handle the case of a key not existing for you, and give you a (changable) fallback value instead in that case. get将处理您不存在的键的情况,并在这种情况下为您提供一个(可变的)后备值。 You'll still need to handle the first IndexError manually, but all the ones that are just except KeyError: will disappear. 您仍然需要手动处理第一个IndexError ,但是except KeyError:都将消失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM