What is the EAFP principle in Python?

前端 未结 3 1527
自闭症患者
自闭症患者 2020-11-21 22:44

What is meant by \"using the EAFP principle\" in Python? Could you provide any examples?

3条回答
  •  半阙折子戏
    2020-11-21 22:45

    From the glossary:

    Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

    An example would be an attempt to access a dictionary key.

    EAFP:

    try:
        x = my_dict["key"]
    except KeyError:
        # handle missing key
    

    LBYL:

    if "key" in my_dict:
        x = my_dict["key"]
    else:
        # handle missing key
    

    The LBYL version has to search the key inside the dictionary twice, and might also be considered slightly less readable.

提交回复
热议问题