Python raise from和raise的区别

def reduce(f,*args):
    if not (1 <= len(args) <= 2): # if undecodedable arguments
        if len(args) < 1:
            raise TypeError('reduce expected at least 2 arguments, got '+str(len(args)))
        else:
            raise TypeError('reduce expected at most 3 arguments, got '+str(len(args)))

    iterable = args[0]

    i = iter(iterable)            # create iterator
    try:                          # try (to handle empty iterator if no unit)
        a = args[1] if len(args) == 2 else next(i)
                                  # use unit or get first value
        while True:               # while (to process more values in iterator)
            try:                  #   try (to determine if more values)
                a = f(a,next(i))  #     get next/f combines with previous result
            except StopIteration: #   when no more values in iterator
                return a          #     return reduced/accumulated result
    except StopIteration:         # empty iterator (with no unit): raise exception
        raise TypeError('reduce() of empty sequence with no initial value') from None
    
Note that
  reduce(operator.add, [])     raises a TypeError Exception
    TypeError: reduce() of empty sequence with no initial value
  reduce(operator.add, [],  0) returns  0 (the unit)
  reduce(operator.add, [5])    returns  5
  reduce(operator.add, [5], 0) returns  5 (the unit, 0, + the first value)
  reduce(operator.add, [5], 5) returns 10 (the unit, 5, + the first value)

Note the "from None" in the last line. If we raise an exception while handling
an exception in Python, both exceptions appear in the trace. But the TypeError
exception is what we want to communicate (the StopIteration exception was just
how we know there is a problem) so by including "from None" it instructs Python
to remove the StopIteration exception from the trace.
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CCF小彤

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值