- 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.