eleanora eleanora - 4 months ago 8
Python Question

How to write multiple try/excepts efficiently

I quote often want to try to convert values to int and if they can't be converted, set them to some default value. For example:

try:
a = int(a)
except:
a = "Blank"
try:
b = int(b)
except:
b = "Blank"
try:
c = int(c)
except:
c = "Blank"


Can this be written more efficiently in Python rather than having to write out every try and except?

Answer

I'd simply use a function:

def int_with_default(i):
    try:
        return int(i)
    except ValueError:
        return "Blank"

a = int_with_default(a)
b = int_with_default(b)
c = int_with_default(c)

If necessary, you can always add a second argument that tells what the default value should be if you don't want to use "Blank" every time.