my_functions = [func1, func2, func3]
for func in my_functions:
returned_val = func()
if 'content' in returned_val: # checks for 'content' key in returned `dict`
value = returned_val['content']
break
from iteration_utilities import first
# The logic that you want to execute for each function (it's the same for each function, right?)
def doesnt_error(func):
try:
return func()['content']
except (KeyError, TypeError):
return False
# some sample functions
func1 = lambda: None
func2 = lambda: {}
func3 = lambda: {'content': 'what?'}
# A tuple containing all functions that should be tested.
functions = (func1, func2, func3)
# Get the first result of the predicate function
# the `retpred`-argument ensures the function is only called once.
value = first(functions, pred=doesnt_error, retpred=True)
def try_run(func_list, field, default_value):
for f in func_list:
try:
value = f()[field]
return value
except (TypeError, KeyError):
pass
return default_value
try_run([someFunction, someOtherFunction], 'content', 'no content')
由于返回的值是
dict
类型,因此可以使用dict.get
在一行中实现与以下相同的行为:但是如果您只处理问题中提到的两个值,那么这将是适用的。为了处理多个函数链,您可以创建一个函数列表,并在返回的dict对象中检查“key”,如下所示:
这需要一个外部库,但您可以使用^{} :
1这是我写的第三方库:^{} 。
你喜欢这个工作吗?你知道吗
Sample Code
相关问题 更多 >
编程相关推荐