“Ask forgiveness not permission” - explain

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

    While there's already a number of high quality answers, most primarily discuss this from a stylistic stand point, as appose to a functional one.

    There are certain cases where we need to ask forgiveness, not permission to insure correct code (outside of a multithreaded programs).

    A canonical example being,

    if file_exists: 
        open_it()
    

    In this example, the file could have been deleted between the check and trying to actually open the file. This is avoided by using try:

    try:
        open_it()
    except FileNotFoundException:
        pass # file doesn't exist 
    

    This crops up in a variety of places, often working with filesystems or external APIs.

提交回复
热议问题