What is EAFP?
EAFP (Easier to Ask for Forgiveness than Permission) is a coding style that’s commonly used in Python community. This coding style assumes that needed variables, files, etc. exist. Any problems are caught as exceptions. This results in a generally clean and concise style containing a lot of try and except statements. This technique really contrasts with common style in many other languages like C with the LBYL (Look Before You Leap) approach which is characterized by the presence of many if statements.
Example:
We have some old code on exporting some excel file, if we already have some file with the same name on the temporary folder, we’ll delete it.
import os
if os.path.exists("something.xlsx"): # violates EAFP coding style os.unlink("something.xslx ")EAFP coding style prefers writing code like this:
import os
try: os.unlink("something.xlsx ")except OSError: # raised when file does not exist passUnlike the original code, the modified code simply assumes that the needed file exists, and catches any problems as exceptions. In the example above, if the file does not exist, the problem will be caught as an OSError exception.