Skip to content
Related Articles

Related Articles

EAFP Principle in Python

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 10 May, 2020
View Discussion
Improve Article
Save Article

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:




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"


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.




# 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())


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
Recommended Articles
Page :

Start Your Coding Journey Now!