Is it possible to use try catch block inside of a lambda function. I need the lambda function to convert a certain variable into an integer, but not all of the values will be able to be converted into integers.
Advertisement
Answer
Nope. A Python lambda can only be a single expression. Use a named function.
It is convenient to write a generic function for converting types:
JavaScript
x
8
1
def tryconvert(value, default, *types):
2
for t in types:
3
try:
4
return t(value)
5
except (ValueError, TypeError):
6
continue
7
return default
8
Then you can write your lambda:
JavaScript
1
2
1
lambda v: tryconvert(v, 0, int)
2
You could also write tryconvert()
so it returns a function that takes the value to be converted; then you don’t need the lambda:
JavaScript
1
14
14
1
def tryconvert(default, *types):
2
def convert(value):
3
for t in types:
4
try:
5
return t(value)
6
except (ValueError, TypeError):
7
continue
8
return default
9
# set name of conversion function to something more useful
10
namext = ("_%s_" % default) + "_".join(t.__name__ for t in types)
11
if hasattr(convert, "__qualname__"): convert.__qualname__ += namext
12
convert.__name__ += namext
13
return convert
14
Now tryconvert(0, int)
returns a function convert_0_int
that takes a value and converts it to an integer, and returns 0
if this can’t be done. You can use this function right away (not saving a copy):
JavaScript
1
2
1
mynumber = tryconert(0, int)(value)
2
Or save it to call it later:
JavaScript
1
4
1
intconvert = tryconvert(0, int)
2
# later...
3
mynumber = intconvert(value)
4