如果在Python中的语句中间抛出异常,则返回None

时间:2017-10-07 07:11:27

标签: python

我有多行来解码来自多个大JSON文件的一些参数,由于某些分支是可选的,在某些文件中可能不存在,因此它们可能在结构上有细微差别。代码如下:

a = content['x'].findAll('div')[0]['y'].find(id='z').html.text
b = content['t'].findAll('a')[1].finaAll('b')[2]['y'].text
c = content['q'].find(id='f')[4].text
...

因为它可能在任何地方都返回None,所以在尝试填充值abc等时可能会抛出异常...你怎么能写一个包装器函数可以如下所示:当抛出任何异常时,只返回None。

a = get_or_none(content['x'].findAll('div')[0]['y'].find(id='z').html.text)
b = get_or_none(content['t'].findAll('a')[1].finaAll('b')[2]['y'].text)
c = get_or_none(content['q'].find(id='f')[4].text)
...

由于a,b和c等变量太多,所以我不想为我的代码的每一行写try..except。有什么建议?谢谢!

2 个答案:

答案 0 :(得分:3)

a = get_or_none(content['x'].findAll('div')[0]['y'].find(id='z').html.text)的问题是get_or_none函数无法捕获content['x'].findAll(...)中抛出的异常,因为该代码在 get_or_none之前执行甚至被称为。

要解决此问题,您必须延迟执行此代码,直到您进入get_or_none。这对于lambda来说最简单:

a = get_or_none(lambda: content['x'].findAll('div')[0]['y'].find(id='z').html.text)

现在,在我们调用lambda函数之前,代码不会被执行。因此,我们可以将get_or_none定义为:

def get_or_none(func):
    try:
        return func()
    except Exception:
        return None

答案 1 :(得分:0)

我的评论可能有问题。我实际上在想这样的事情。但这与我的“基本”知识相去甚远。我只想简化问题 - 可能对某些人有用,但不要把它当作“最佳答案”。

从这里采用的例子: https://www.programiz.com/python-programming/decorator

def ordinary(string):
    return int(string)

# normal function
print(ordinary("2")) # returns 2

现在让我们改变这个功能:

# a function that enhances a function
def enhance(func):
    def inner(string):
        try:
            return func(string)
        except:
            return None
    return inner

# now let's enhance it assigning it to a variable name
# this is the 'decorate' part
get_or_none = enhance(ordinary)

# use new function
print(get_or_none("a")) # returns None
print(get_or_none("12")) # return 12

# old function will throw an error still
print(ordinary("a")) # throws an error