Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python map exception continue mapping execution

The following example is very simple. I want to execute map() with a function which can raise Exception. It will be more clearly with an example :

number_list = range(-2,8)

def one_divide_by(n):
    return 1/n

try:
    for number, divide in zip(number_list, map(one_divide_by, number_list)):
        print("%d : %f" % (number, divide))
except ZeroDivisionError:
    # Execution is stopped. I want to continue mapping
    pass

When I execute this code I get :

-2 : -0.500000
-1 : -1.000000

It's due to the 0 in my list. I don't want remove this 0 (because in real case I can't know first if I will get Exception). Do you know how to continue mapping after the exception ?

like image 786
Samuel Dauzon Avatar asked Sep 25 '15 10:09

Samuel Dauzon


2 Answers

you could catch the exception in your function (instead of in the for loop) and return None (or whatever you choose) if ZeroDivisionError is raised:

def one_divide_by(n):
    try:
        return 1/n
    except ZeroDivisionError:
        return None

if you choose to return None you need to adapt your format string; None can not be formatted with %f.

other values you could return (and that would be compatible with your string formatting) are float('inf') (or float('-inf') depending on the sign of your numerator) or float('nan') - "infinity" or "not a number".

here you will find some of the caveats of using float('inf').

like image 99
hiro protagonist Avatar answered Oct 02 '22 18:10

hiro protagonist


You can move the try/except block inside the function. Example -

def one_divide_by(n):
    try:
        return 1/n
    except ZeroDivisionError:
        return 0   #or some other default value.

And then call this normally, without a try/except block -

for number, divide in zip(number_list, map(one_divide_by, number_list)):
    print("%d : %f" % (number, divide))
like image 44
Anand S Kumar Avatar answered Oct 02 '22 19:10

Anand S Kumar