EAFP Coding Style in Python

time to read 1 min | 186 words

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.


Related Post:

  1. May 25, 2017 New interesting data structures in Python 3
  2. May 22, 2017 Keyword argument demystify
  3. May 04, 2017 Looping techniques in Python
  4. May 03, 2017 Enhance your tuples
  5. May 02, 2017 Get more with collections!
  6. May 01, 2017 There is more to copying
  7. Apr 30, 2017 Implementing weak references in Python
  8. Apr 26, 2017 Next, Function or Method ?
  9. Apr 24, 2017 Generator Expressions
  10. Apr 23, 2017 Yield Keyword
  11. Apr 21, 2017 What are Generators?
  12. Apr 16, 2017 Lambda Functions in Python
  13. Apr 06, 2017 Function in Python are First-Class Object
  14. Apr 05, 2017 Django 1.11 Release Note a Reading
  15. Apr 03, 2017 One Hell Named JSON
  16. Dec 26, 2016 Queue in Python - Part 3
  17. Nov 02, 2016 Queue in Python - Part 2
  18. Nov 02, 2016 Queue in Python - Part 1
  19. Jun 25, 2016 Enable Spark Context on Your Ipython Notebook
  20. Jul 24, 2014 Kompresi CSS menggunakan Python