4

I'm a user of R, but have to learn Python for a school project. Now, in R, I frequently use the base function stop in my code, and I'd like to know how to emulate this functionality in Python. For a concrete example, take this R code:

add.two <- function(t) {
     if (!is.numeric(t)) stop('Please make t numeric.')
     t + 2
}

This function does three things, (i) it adds two to (e.g.) a numeric vector, (ii) if it is passed a non-numeric argument it returns a personal, concise, and easy to understand error message, and (iii) it ceases the function from running any further in the case that t is non-numeric. My first attempt for how to do this in Python is

def add_two(t):
    if not ( isinstance(t, int) or isinstance(t, float) ):
        print('Error: Please make t numeric.')
    else:
        print(t+2)

However, this only does things (i) and (ii). In other words, if the body of this function were longer (although, in this example, it is not), Python would not know to stop running. Another option is

def add_two(t):
    if not ( isinstance(t, int) or isinstance(t, float) ):
        print('Error: Please make t numeric.')
        raise
    else:
        print(t+2)

Which, I suppose, does things (i) and (iii), but the error message is at best cluttered and confusing, and at worst incorrect and misleading.

Does someone know of a way to achieve all three goals in Python? Thank you for your time.

Edit: IDK why, I said 'error' instead of 'stop' just a brain fart.

2
  • 2
    If you want to stop the function use return, if you want to stop the whole script raise an exception Commented Jan 7, 2020 at 22:16
  • 2
    And you can do isinstance(t, (int, float)) Commented Jan 7, 2020 at 22:16

2 Answers 2

4

Use the raise keyword while creating an Exception object. You can customize the message with an argument:

def add_two(t):
    if not (isinstance(t, int) or isinstance(t, float)):
        raise ValueError('t must be numeric')
    else:
        print(t + 2)

Like most programming languages, there are different types of exceptions to represent different types of faults. The list of those is here, and you can of course make custom Exception subclasses if you want your own custom exception types.


In your case, though, this isn't so much necessary. If you do

def add_two(t):
    print(t + 2)

then an error will be thrown anyway if t is of a type that you can't add an integer to (e.g. a string - a TypeError will be raised). Python typically advocates doing this when possible: "ask forgiveness rather than permission".

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

4 Comments

So, thank you firstly. That definitely seems like a step in the right direction, but the error message still, shall I say, tries to be more than I think it should/needs to be. It returns that Traceback stuff. It seems like this is considered a feature and not a defect, but just out of curiosity, is there any way to get the error to consist solely of text which I choose?
The traceback is for the benefit of the programmer, and is actually separate from the message. When you don't handle the exception with a try/except block (akin to a try/catch pair in, say, Java - I don't know how things work in R), the default behavior is to print the error message, and then print a stack trace so that the programmer can figure out where and why the error occurred, so they can fix it. If you don't want the traceback to be printed, add a try/except block to the code that calls this function, and just print the exception's .message attribute.
@ThomasWinckelman See also the docs on handling exceptions
Thanks for the suggestion, I'll look into that! I will admit I've been procrastinating learning that try/except deal, because there is no analog in R. That said, the attempt to procrastinate learning this was probably futile.
1

One option is using:

raise ValueError('your error message here')

This will throw an error with the custom message you want.

Comments

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.