Python异常:EAFP和什么是真正的异常? [英] Python Exceptions: EAFP and What is Really Exceptional?

查看:93
本文介绍了Python异常:EAFP和什么是真正的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在几个地方已经说过(这里 here ),Python强调要求豁免比许可更容易(EAFP)应该是温和的想法是,异常只能在真正特殊情况下被称为。考虑以下内容,我们在其中弹出并推送优先级队列,直到只剩下一个元素:

It's been said in a couple places (here and here) that Python's emphasis on "it's easier to ask for forgiveness than permission" (EAFP) should be tempered with the idea that exceptions should only be called in truly exceptional cases. Consider the following, in which we're popping and pushing on a priority queue until only one element is left:

import heapq
...
pq = a_list[:]
heapq.heapify(pq)
while True:
    min1 = heapq.heappop(pq)
    try:
        min2 = heapq.heappop(pq)
    except IndexError:
        break
    else
        heapq.heappush(pq, min1 + min2)
# do something with min1

该异常仅在 len(a_list)循环的迭代,但它并不是特别的,因为我们知道它将最终发生。这个设置可以帮助我们检查 a_list 是否为空,但是(也许)它比使用显式条件更不可读。

The exception is only raised once in len(a_list) iterations of the loop, but it's not really exceptional, because we know its going to happen eventually. This setup saves us from checking whether a_list is empty a bunch of times, but (maybe) it's less readable than using explicit conditions.

对这种非特殊程序逻辑使用异常有什么共识?

What's the consensus on using exceptions for this kind of non-exceptional program logic?

推荐答案


异常只能在
中调用真正例外情况

exceptions should only be called in truly exceptional cases

不在Python中:例如, $ c> s)被抛出并被捕获的异常( StopIteration )终止。所以,每个循环发生一次的异常对于Python来说并不陌生 - 它往往比较常见!

Not in Python: for example, every for loop (unless it prematurely breaks or returns) terminates by an exception (StopIteration) being thrown and caught. So, an exception that happens once per loop is hardly strange to Python -- it's there more often than not!

所讨论的原则在其他语言中可能至关重要,但是这个原则绝对没有理由适用于Python,它与语言的精神非常相反。

The principle in question may be crucial in other languages, but that's definitely no reason to apply that principle to Python, where it's so contrary to the language's ethos.

在这种情况下,我喜欢Jon的重写(应该通过删除进一步简化其他分支),因为它使代码更紧凑 - 一个务实的原因,绝对不是外来原则的Python风格的回火。

In this case I like Jon's rewrite (which should be further simplified by removing the else branch) because it makes the code more compact -- a pragmatical reason, most definitely not the "tempering" of Python style with an alien principle.

这篇关于Python异常:EAFP和什么是真正的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆