EAFP vs LBYL
PronunciationEE-ap vee-ess EL-bul
Definition
EAFP ("easier to ask forgiveness than permission") means trying the action and handling the error if it fails. LBYL ("look before you leap") means checking first, then acting.
Where you hear it
In Python style discussions, code reviews about try / except versus if, and interviews about Pythonic code.
Examples
EAFP: try to open the file and catch
FileNotFoundError.LBYL: check that the file exists before opening it.
The EAFP version opens the file and catches the error, instead of checking first.
Common mistake
Using try/except for everything, or wrapping a huge block. Keep the try small and catch only the error you expect.
Don't confuse with
Both styles guard the same operation. LBYL checks the condition first, and the situation can change before you act. EAFP acts first and handles the failure, which is safer when another process can change the state between the check and the action.
Say it at work
- In a meeting or chat
Python prefers EAFP, so just try it and handle the exception.
- In an email or ticket
Here LBYL is clearer because the check is cheap.
Keep exploring
More in Programming Fundamentals