31

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?

2
  • 1
    Possible duplicate of Manually raising (throwing) an exception in Python. That question handles how to manually raise an error, which prevents the script from continuing after returning from a function. Commented Nov 27, 2015 at 17:26
  • 1
    return will not continue to execute the function Commented Nov 27, 2015 at 17:28

2 Answers 2

77

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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.

2 Comments

I think raising an error instead of a hard coded value is much more elegant and safer.
I agree with @MattSom, raising an error is a much better practice than returning a number

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.