我有多行代码来解码多个大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,所以在尝试填充值a
、b
、c
等时可能会引发异常。。。你怎么能写一个包装函数,它的行为如下:当抛出任何异常时,只返回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..除了我的每一行代码。有什么建议吗?谢谢!你知道吗
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
最简单:在调用lambda函数之前,代码不会被执行。因此,我们可以将
get_or_none
定义为:我的评论可能错了。实际上我在想这样的事情。但这与我的“基本”知识相去甚远。我只是喜欢简化问题——可能对某人有用,但不要把它当作“最佳答案”。你知道吗
此处采用的示例: https://www.programiz.com/python-programming/decorator
现在让我们改变这个函数:
相关问题 更多 >
编程相关推荐