EAFP is a piece of gem advice in the Python community which may not be familiar to programmers of other communities. Quickly, EAFP or ‘Easier to Ask for Forgiveness than Permission’ means holding an optimistic view for the code you are working on, and if an exception is thrown catch it and deal with it later.
“Always remember that it’s much easier to apologize than to get permission. In this world of computers, the best thing to do is to do it.” — Grace Hopper
It is unlike the traditional method of LBYL or ‘Look Before You Leap’, where you check whether your code will succeed and proceed if and only if there is no error.
Example: Suppose you want to open a file and read its contents.
When you ask for permission to read the file, the answer is ‘Yes’, but by the time you actually go for reading the answer is changed. This is where you open yourself to the Race condition.
‘Forgiveness’ code: What you should do instead is go ahead with the flow and ask for forgiveness i.e catch the error using Exception handling.
The Advantages of the EAFP method:
- Explicit is better than implicit
- Fail, but Fail fast and Succeed faster
- Fail, but Fail cheap
- Don’t repeat yourself
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.