LoginSignup
1
1

More than 5 years have passed since last update.

EP 14 Prefer Exceptions to Returning `None`

Posted at
  • Functions that return None to indicate special meaning are error prone because None and other values (e.g. zero, the empty string) all evalute to False in coditional expressions.
  • Raise exceptions to indicate special situations instead of returning None. Expect the calling code to handle exceptions properly when they're documented.

Effective Python

Compare None with is operator

def divide(a, b):
    try:
        return a/b
    except ZeroDivisionError:
        return None

None is error prone

result = divide(x, y)
if result is None:
  print('Invalid inputs')

Compare None with is operator

x, y = 0, 5
result = divide(x, y)
if not result:
  print('Invalid inputs')

To avoid this case:

  • to split the return value into a two tuple.(like Golang but I never see this pattern in python)
  • raise an exception up to the caller and make them deal.

1.

def divide(a, b):
    try:
        return True, a/b
    except ZeroDivisionError:
        return False, None

2.

def divide(a, b):
    try:
        return a/b
    except ZeroDivisionError as e:
        raise ValueError('Invalid inputs') from e

Make sure that you document this behavior.

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1