为什么要“宽恕而不是得到许可”?在Python中? [英] Why is it "easier to ask forgiveness than it is to get permission" in Python?

查看:92
本文介绍了为什么要“宽恕而不是得到许可”?在Python中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么比获得许可更容易请求宽恕( EAFP )被认为是Python的良好做法?作为一个编程新手,我的印象是,与使用其他检查相比,使用许多 try ... except 例程将导致rather肿且可读性差的代码。

Why is "Easier to Ask Forgiveness than it is to get Permission" (EAFP) considered good practice in Python? As a programming novice I have the impression that using many try...except routines will rather lead to bloated and less readable code than compared to using other checks.

EAFP方法的优势是什么?

What is the advantage of the EAFP approach?

NB:我知道这里也有类似的问题,但是它们主要是指一些特定的示例,而我对该原理背后的哲学更感兴趣。

NB: I know there are similar questions here, but they mostly refer to some specific example, while I am more interested in the philosophy behind the principle.

推荐答案

LBYL ,它是 EAFP 与断言没有任何关系,它只是意味着您在尝试访问可能会导致错误的内容之前添加了一个检查。

LBYL, the counter approach to EAFP doesn't have anything to do with assertions, it just means that you add a check before you try to access something that might not be there.

Python之所以是EAFP,是因为与其他语言(例如Java)不同-在Python中捕获异常是相对便宜的操作,所以这就是为什么

The reason that Python is EAFP is that unlike other languages (Java for example) - in Python catching exceptions is relatively inexpensive operation, and that's why you're encouraged to use it.

EAFP示例:

try:
    snake = zoo['snake']
except KeyError as e:
    print "There's no snake in the zoo"
    snake = None

LBYL示例:

if 'snake' in zoo:
    snake = zoo['snake']
else:
    snake = None

这篇关于为什么要“宽恕而不是得到许可”?在Python中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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