GPB
GPB

Reputation: 2495

Python Return error from function

I am writing a python function which uses two arrays of equal size [n,1]. Before performing any calculations, I'd like to check to ensure the lengths are the same, and if not, return an error. What is the best practice?

def do_some_stuff(array1, array2): 
# Before doing stuff, check to ensure both arrays have the same length

if len(array1) != len(array2):
#  Break and return with error

I'm confused, because I want to break and return an error code (say -1). Seems that break will return without any value, and return will continue to execute the function? Or does Return break out of any remaining code?

Upvotes: 31

Views: 142324

Answers (2)

memoselyk
memoselyk

Reputation: 4118

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.

Upvotes: 77

k4ppa
k4ppa

Reputation: 4667

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.

Upvotes: 4

Related Questions