darksideofthesun
darksideofthesun

Reputation: 621

Proper way to handle exception when function returns None

What's the best way to handle a case where a function returns None. For example:

def my_function():
     if <some_stuff_works>:
         return <stuff>
     else:
         return None

my_var = my_function()

What I'd like to do is raise an exception if my_var is None and then set to a certain value. So something like:

try:
    my_var = my_function()
except ValueIsEmpty:
    my_var = "EMPTY"

Does that make sense?

Upvotes: 0

Views: 154

Answers (3)

Mathieu Paturel
Mathieu Paturel

Reputation: 4500

You can do this:

var = my_function() or 'default_value'

But, var will be equal to 'default_value' when my_function returns

  • None (what you want)
  • False
  • 0
  • empty list [] (thanks to @roganjosh)

Up to you to choose what you want. If you don't what this, @brianpck's answer's still the best one.

You also make the function raise an exception instead of returning None.

def my_function():
    if <some_stuff_works>:
        return <stuff>
    else:
        raise SomeException # maybe TypeError, whatever

And then call it like this:

try:
    result = my_function()
except SomeException:
    result = 'EMPTY'

Or even better:

def my_function():
    if <some_stuff_works>:
        return <stuff>
    # no need for the else because return end up the function execution.
    # so if it returns <stuff>, it will stop, and not look further
    return 'EMPTY'

Upvotes: 0

CAB
CAB

Reputation: 1148

Since you're want to use exceptions, try this;

def my_function():
     if <some_stuff_works>:
         return <stuff>
     raise ValueError

try:
    my_var = my_function()
except ValueError:
    my_var = "EMPTY"

Upvotes: 1

brianpck
brianpck

Reputation: 8254

If you can't modify the function, there's no need to come up with a creative exception: just check if it is None and give it an appropriate value.

my_var = my_function()
if my_var is None:
    my_var = 'default_value'

Upvotes: 3

Related Questions