EAFP Coding Style in Python
Mon Apr 27, 2015 · 186 words
Python Coding Style EAFP

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 is really contrasts with common style in many other language like C with 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 prefer our code like this:

import os

try:
    os.unlink("something.xlsx ")
except OSError:  # raised when file does not exist
    pass

Unlike the original code, the modified code simply assumes that the needed file exists, and catches any problems as exceptions. For example above, if the file does not exist, the problem will be caught as an OSError exception.


back · he thought · he could · so he did · main