Effective Python (Functions)

  • Prefer Exceptions to Returning None

Functions that return None to indicate special meaning are error prone because None and other values (e.g., zero, the empty string) all evaluate to False in conditional expressions.

Raise exceptions to indicate special situations instead of returning None. Expect the calling code to handle exceptions properly when they’re documented. 

# In the case of dividing by zero, returning None seems natural because the result is undefined.
def divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        return None
result = divide(x, y)
if result is None:
    print('Invalid inputs')
# You may accidentally look for any False equivalent value to indicate errors instead of only looking for None
x, y = 0, 5
result = divide(x, y)
if not result:
    print('Invalid inputs')    # This is wrong!
# 这是一个常见的Python错误代码当None有特殊含义的时候。
# 这也是为什么使用None作为函数的返回值是容易出错的,有两种方法可以解决这个问题:

# 1,将结果作为一个两值的元组返回;第一个值为操作成功/失败,第二个值为真实的结果
def divide(a, b):
    try:
        return True, a / b
    except ZeroDivisionError:
        return False, None
success, result = divide(x, y)
if not success:
    print('Invalid inputs')
# 你或许会使用下划线“_”来忽略第一个值,但这样就跟直接返回None一样,容易出错
_, result = divide(x, y)
if not result:
    print('Invalid inputs')

# 2,较好的方法是,从不返回None,而是抛出一个异常给调用者让其去处理
# 在这里将ZeroDivisionError转换为ValueError已暗示调用者,输入值是错误的
def divide(a, b):
    try:
        return a / b
    except ZeroDivisionError as e:
        #raise ValueError('Invalid inputs') from e    # Python3
        raise ValueError('Invalid inputs %s' % str(e))    # Python2
x, y = 5, 2
try:
    result = divide(x, y)
except ValueError:
    print('Invalid inputs')
else:
    print('Result is %.1f' % result)










你可能感兴趣的:(Effective Python (Functions))