What is meant by "using the EAFP principle" in Python? Could you provide any examples?
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
andexcept
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.