“Ask forgiveness not permission” - explain

前端 未结 8 1702
长情又很酷
长情又很酷 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:18

    My personal non-religious opinion is that said mantra applies mainly to documented and well understood exit conditions and edge cases (e.g. I/O errors), and should never be used as a get-out-of-jail card for sloppy programming.

    That said, try/except is often used when "better" alternatives exist. For example:

    # Do this    
    value = my_dict.get("key", None)
    
    # instead of this
    try:
      value = my_dict["key"]
    except KeyError:
      value = None
    

    As for your example, do use if hasattr(foo, "bar") if your have no control over foo and need to check conformance with your expectations, otherwise simply use foo.bar and let the resulting error be your guide to identifying and fixing sloppy code.

提交回复
热议问题