“Ask forgiveness not permission” - explain

前端 未结 8 1611
长情又很酷
长情又很酷 2020-11-22 02:02

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

I understand this phrase is one of several litmus t

8条回答
  •  误落风尘
    2020-11-22 02:26

    In the Python context "Ask forgiveness not permission" implies a style of programming where you don't check for things to be as you expect beforhand, but rather you handle the errors that result if they are not. The classical example is not to check that a dictionary contains a given key as in:

    d = {}
    k = "k"
    if k in d.keys():
      print d[k]
    else:
      print "key \"" + k + "\" missing"
    

    But rather to handle the resulting error if the key is missing:

    d = {}
    k = "k"
    try:
      print d[k]
    except KeyError:
      print "key \"" + k + "\" missing"
    

    However the point is not to replace every if in your code with a try/except; that would make your code decidedly messier. Instead you should only catch errors where you really can do something about them. Ideally this would reduce the amount of overall error handling in your code, making its actual purpose more evident.

提交回复
热议问题