“请求宽恕而不是许可"- 解释 [英] "Ask forgiveness not permission" - explain

查看:54
本文介绍了“请求宽恕而不是许可"- 解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不是在询问关于这种哲学的个人宗教"意见,而是一些更具技术性的意见.

I'm not asking for personal "religious" opinions about this philosophy, rather something a bit more technical.

我知道这句话是测试您的代码是否pythonic"的几个试金石之一.但对我来说,pythonic 意味着干净、简单和直观,不会为糟糕的编码加载异常处理程序.

I understand this phrase is one of several litmus tests to see if your code is "pythonic". But to me, pythonic means clean, simple and intuitive, not loaded with exception handlers for bad coding.

所以,实际例子.我定义了一个类:

So, practical example. I define a class:

class foo(object):
    bar = None

    def __init__(self):
        # a million lines of code
        self.bar = "Spike is my favorite vampire."
        # a million more lines of code

现在,来自程序背景,在另一个函数中我想这样做:

Now, coming from a procedural background, in another function I wanna do this:

if foo.bar:
    # do stuff

如果我不耐烦并且没有做初始的 foo = None,我会得到一个属性异常.所以,请求宽恕而不是许可"建议我应该这样做?

I'll get an attribute exception if I was impatient and did not do the initial foo = None. So, "ask forgiveness not permission" suggests I should do this instead?

try:
    if foo.bar:
        # do stuff
except:
    # this runs because my other code was sloppy?

为什么我最好在 try 块中添加额外的逻辑以便我可以让我的类定义更加模糊?为什么不一开始就定义所有内容,从而明确授予权限?

Why would it be better for me to add additional logic in a try block just so I can leave my class definition more ambiguous? Why not define everything initially, therfore explicitly grant permission?

(不要因为使用 try/except 块而责备我......我到处都使用它们.我只是认为使用它们来捕获我自己的错误是不正确的,因为我不是一个彻底的程序员.)

(Don't beat me up about using try/except blocks... I use them everywhere. I just don't think it's right to use them to catch my own errors because I wasn't a thorough programmer.)

或者...我是否完全误解了请求宽恕"的口头禅?

Or... do I completely misunderstand the "Ask Forgivess" mantra?

推荐答案

经典的请求宽恕而不是许可"示例是从可能不存在的 dict 访问值.例如:

The classical "ask forgiveness not permission" example is accessing values from a dict that may not exist. E.g.:

names = { 'joe': 'Joe Nathan', 'jo': 'Jo Mama', 'joy': 'Joy Full' }
name = 'hikaru'

try:
    print names[name]
except KeyError:
    print "Sorry, don't know this '{}' person".format(name)

此处说明了可能发生的异常 (KeyError),因此您不会为可能发生的每个错误请求宽恕,而只是针对自然发生的错误请求宽恕.相比之下,先征求许可"的方法可能如下所示:

Here the exception that might occur (KeyError) is stated, so that you're not asking forgiveness for every error that might occur, but only the one that would naturally occur. For comparison, the "ask permission first" approach might look like:

if name in names:
    print names[name]
else:
    print "Sorry, don't know this '{}' person".format(name)

real_name = names.get(name, None)
if real_name:
    print real_name
else:
    print "Sorry, don't know this '{}' person".format(name)

这种请求原谅"的例子往往过于简单.IMO 不清楚 try/except 块本质上比 if/else 更好.当执行可能以多种方式失败的操作时,真正的价值要清楚得多——比如解析;使用 eval();访问操作系统、中间件、数据库或网络资源;或进行复杂的数学运算.当存在多种潜在的故障模式时,准备好接受宽恕是非常有价值的.

Such examples of "ask forgiveness" are often too simple. IMO it's not crystal clear that try/except blocks are inherently better than if/else. The real value is much clearer when performing operations that might fail in a variety of ways--such as parsing; using eval(); accessing operating system, middleware, database, or network resources; or performing complex mathematics. When there are multiple potential failure modes, being prepared to get forgiveness is hugely valuable.

关于您的代码示例的其他说明:

Other notes about your code examples:

您不需要在每个变量用法周围包 try/except 块.那将是可怕的.而且您不需要在 __init__() 中设置 self.bar ,因为它是在上面的 class 定义中设置的.通常在类中定义它(如果它的数据可能在类的所有实例之间共享)或在 __init__() (如果它是实例数据,特定于每个实例).

You do not need to ladle try/except blocks around every variable usage. That would be horrible. And you don't need to set self.bar in your __init__() since it's set in your class definition above. It is usual to define it either in the class (if it's data likely to be shared among all instances of the class) or in the __init__() (if it's instance data, specific to each instance).

顺便说一下,None 的值不是未定义或错误.它是一个特定且合法的值,表示无、无、空或无.许多语言都有这样的值,所以程序员不会重载"0-1''(空字符串)或类似的有用值.

A value of None is not undefined, or an error, by the way. It's a specific and legitimate value, meaning none, nil, null, or nothing. Many languages have such values so programmers don't "overload" 0, -1, '' (empty string) or similar useful values.

这篇关于“请求宽恕而不是许可"- 解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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