alphanumeric alphanumeric - 1 month ago 4
Python Question

How to return from function if argument is not supplied using Exception

To make sure the function is passed a correct argument I always start a function definition with if statement to check the argument for validity:

def func(arg=None):
if not isinstance(arg, int): return
return arg+2

func('a')
print 'this is the end line'


While it works for me well, I wonder if there is more Pythonic way of doing it.
I do like the
Exception
approach. But I don't want the exception to crash the entire process just because of one of the arguments was not supplied or if it is not what the function expects:

def func(arg=None):
if not isinstance(arg, int):
raise ValueError('expected integer. receivd: %s instead'%type(arg))
return arg+2



func('a')
print 'this is the end line'


Results to a process crash without ever reaching the end line throwing this Traceback:

Traceback (most recent call last):
File "test.py", line 17, in <module>
func('a')
File "test.py", line 12, in func
raise ValueError('expected integer. receivd: %s instead'%type(arg))
ValueError: expected integer. receivd: <type 'str'> instead
[Finished in 0.0s with exit code 1]


I also would like to avoid
try
approach as well. Since it introduces more complexity to the code.

Answer

When a function raises an exeption, whoever calls the function is responsible for catching any exception it may throw.

try:
    func(a)
except ValueError as e:
    print e
print "This is the end."

Or, alternatively, if you just want the exception to be printed as Python normally would, but still finish the script, use a finally clause:

try:
    func('a')
finally:
    print "This is the end."

(The exception traceback will be printed after the "This is the end message" from the script, somewhat counterintuitively.)