Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top