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
- Python | Miscellaneous | Question 2
- Python | Miscellaneous | Question 3
- Python | Miscellaneous | Question 4
- Python | Miscellaneous | Question 5
- Python | Miscellaneous | Question 6
- Data visualization with different Charts in Python
- Implementing web scraping using lxml in Python
- Python | Difference between iterable and iterator
- Python | Word Embedding using Word2Vec
- Debugging Python code using breakpoint() and pdb
- The concept of Social Computing in Python
- How are variables stored in Python - Stack or Heap?
- Source distribution and built distribution in python
- Run python script from anywhere in linux
- __exit__ in Python
- Gradual typing in Python
- Python program to find birthdate on the same day you were born
- Code Golfing in Python
- Hamming Code implementation in Python
- Image Steganography using OpenCV in Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.