Ask for Forgiveness or Look Before You Leap?

Sebastian Witowski
4 min readAug 19, 2020

“Ask for forgiveness” and “look before you leap” (sometimes also called “ask for permission”) are two opposite approaches to writing code. If you “look before you leap”, you first check if everything is set correctly, then you perform an action. For example, you want to read text from a file. What could go wrong with that? Well, the file might not be in the location where you expect it to be. So, you first check if the file exists:

Even if the file exists, maybe you don’t have permission to open it? So let’s check if you can read it:

But what if the file is corrupted? Or if you don’t have enough memory to read it? This list could go on. Finally, when you think that you checked every possible corner-case, you can open and read it:

Depending on what you want to do, there might be quite a lot of checks to perform. And even when you think you covered everything, there is no guarantee that some unexpected problems won’t prevent you from reading this file. So, instead of doing all the checks, you can “ask for forgiveness.”

With “ask for forgiveness,” you don’t check anything. You perform whatever action you want, but you wrap it in a try/catch block. If an exception happens, you handle it. You don't have to think about all the things that can go wrong, your code is much simpler (no more nested ifs), and you will usually catch more errors that way. That's why the Python community, in general, prefers this approach, often called "EAFP" - "Easier to ask for forgiveness than permission."

--

--

Sebastian Witowski

Python consultant and freelancer at switowski.com. Writes about productivity, tools, Python, and programming best practices.