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

2024-09-20 00:05:21 发布

您现在位置: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..除了我的每一行代码。有什么建议吗?谢谢!你知道吗


Tags: or文件代码textdivnoneidget
2条回答

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

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

此处采用的示例: 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

相关问题 更多 >