1

I have multiple functions that might return None:

do_something(), do_something2(), do_something3(), etc.

And to overcome the None Type Errors, from another part of the code I have to hardcode the try-except as such:

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

Is there any way to just apply the same try-except to different lines of code/different function call?

alvas
  • 115,346
  • 109
  • 446
  • 738

2 Answers2

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
Rami
  • 7,162
  • 1
  • 22
  • 19
  • 2
    For this to work for multiple or no arguments you need to include the star (*) also in the function body: `return myFunction(*params)` – skamsie Mar 17 '14 at 07:14
1

I am not a python expert, but I can think another way.

Create an array of the functions and call them in a loop:

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
Raul Guiu
  • 2,374
  • 22
  • 37