Python Return error from function
What is the best practice?
In python code, error conditions are usually indicated with exceptions. You could use raise ValueError("Arrays must have the same size")
.
Using exception rather than return values to indicate errors has the added advantage that the exception would bubble up until it reaches a except
statement. So you can defer the error handling up to a place where it makes sense. Also exceptions have an associated descriptive message instead of a magic number.
The break
statement, as in many other languages, is used to interrupt the flow in loops, like ones created with while
or for
.
You don't need the break
def do_some_stuff(array1, array2): # Before doing stuff, check to ensure both arrays have the same length if len(array1) != len(array2): return -1
Just return the error code. In this way the rest of the code of the function will not be executed.