1

我有多个可能返回的函数None

do_something(), do_something2(),do_something3()

为了克服无类型错误,我必须从代​​码的另一部分硬编码try-except

try:
  x = do_other_things(do_something())
except someError: # because of None Type return
  x = None

try:
  y = do_other_things(do_something2())
except someError: # because of None Type return
  y = None

有什么方法可以将相同的代码应用于try-except不同的代码行/不同的函数调用?

4

2 回答 2

1

我不是 python 专家,但我可以换一种方式思考。

创建一个函数数组并在循环中调用它们:

listOfFuncs = [do_something,do_something2,do_something3]

results = []*len(listOfFuncs)
for index, func in enumerate(listOfFuncs):
    try:
        results[index] = do_other_things(func())
    except someError:
        results[index] = None
于 2014-03-17T07:47:43.920 回答
1

If you are testing for the same exception type, then you can wrap the try/except block into a function that accepts as parameters other function and a list of parameters.

 def try_except(myFunction, *params):
     try:
         return myFunction(*params)
     except ValueError as e:
         return None
     except TypeError as e:
         return None
于 2014-03-17T06:56:58.723 回答