What is the EAFP principle in Python?

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.


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


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

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

Leave a Comment