EAFP Principle in Python

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.

‘Permission’ code:



filter_none

edit
close

play_arrow

link
brightness_4
code

import os
  
  
# Race condition
File_name ="test.txt"
  
if os.access(File_name, os.R_ok):
    with open(File_name) as f:
        print(f.read())
else:
    print("No such file accessed"

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# No Race condition
File_name ="test.txt"
  
try:
    f = open(File_name)
except IOError:
    print("No such file accessed"
else:
    with f:
        print(f.read())

chevron_right


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
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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.


Article Tags :

7


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.