What is the EAFP principle in Python?

Unpaid Oracles picture Unpaid Oracles · Jul 6, 2012 · Viewed 35.5k times · Source

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

Answer

Sven Marnach picture Sven Marnach · Jul 6, 2012

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.