KT100
KT100

Reputation: 1441

Returning error string from a function in python

I have a class function in Python that either returns a success or a failure, but in case of a failure I want it to send a specific error string back. I have 3 approaches in mind:

  1. Pass in an variable error_msg to the function originally set to None and in case of an error, it gets set to the error string. eg:

    if !(foo(self, input, error_msg)):
        print "no error"
    else:
        print error_msg
    
  2. Return a tuple containing a bool and error_msg from the function.

  3. I raise an exception in case of an error and catch it in the calling code. But since I don't see exceptions being used often in the codebase I am working on, so was not too sure about taking this approach.

What is the Pythonic way of doing this?

Upvotes: 4

Views: 24496

Answers (2)

Blender
Blender

Reputation: 298364

Raise an error:

if foo(self, input, error_msg):
    raise SomethingError("You broke it")

And handle it:

try:
    something()
except SomethingError as e:
    print str(e)

It's the Pythonic approach and the most readable.

Returning a tuple like (12, None) may seem like a good solution, but it's hard to keep track of what each method returns if you're not consistent. Returning two different data types is even worse, as it will probably break code that assumes a constant data type.

Upvotes: 7

Simeon Visser
Simeon Visser

Reputation: 122436

Create your own exception and raise that instead:

class MyValidationError(Exception):
    pass

def my_function():
    if not foo():
        raise MyValidationError("Error message")
    return 4

You can then call your function as:

try:
    result = my_function()
except MyValidationError as exception:
    # handle exception here and get error message
    print exception.message

This style is called EAFP ("Easier to ask for forgiveness than permission") which means that you write the code as normal, raise exceptions when something goes wrong and handle that later:

This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

Upvotes: 13

Related Questions