As ruancomelli pointed out, map_except
can drop the offending function call instance from your resulting iterable. This may not be your the desired behaviour.
If you want the offending function call to still appear in the output stream, you can use function composition to transform the exception into something else. For instance, this wrapper:
def zero_div_protect(func):
def wrapper(*args):
try:
return func(*args)
except ZeroDivisionError:
return float('inf')
return wrapper
will take a function (such as one_divide_by
) and return a new function, wrapping the original function with a try:...except:
that returns an "exceptional value" when the exception occurs.
number_list = range(-2, 8)
def one_divide_by(n):
return 1/n
for number, divide in zip(number_list, map(zero_div_protect(one_divide_by), number_list)):
print("%d : %f" % (number, divide))
Output:
-2 : -0.500000
-1 : -1.000000
0 : inf
1 : 1.000000
2 : 0.500000
3 : 0.333333
4 : 0.250000
5 : 0.200000
6 : 0.166667
7 : 0.142857
You can also use zero_div_protect
as a "decorator", which replaces the original function with the wrapped version:
number_list = range(-2,8)
@zero_div_protect
def one_divide_by(n):
return 1/n
for number, divide in zip(number_list, map(one_divide_by, number_list)):
print("%d : %f" % (number, divide))
The output is the same.
See also: functools.wraps for more advanced usages.