Related Articles

Related Articles

EAFP Principle in Python
  • Difficulty Level : Easy
  • Last Updated : 10 May, 2020

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

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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :