skip to content
~/bermudev/blog

Preventing vs Handling Errors in Python

/ 3 min read

If you are a developer like me, you will know that when we are coding we always encounter situations where we have to work with errors or possible errors that may arise during the execution of the code, and here, as in many other cases, there are different ways to approach this.

Today I want to talk about two ways of handling errors, called LBYL and EAFP, and although it may seem that I have pressed random keys on my keyboard, nothing further from reality.

Let’s see.

What is LBYL and EAFP

LBYL stands for ”Look Before You Leap”, what identifies this style is that we first check if something happens and then proceed if this check is positive.

In code it would look something like this:

if can_walk():
    walk()
else:
    do_something_else()

EAFP stands for ”Easier to Ask Forgiveness Than Permission”, and as you can already guess, in this style we try to proceed directly with the code and then handle the possible error.

try:
    walk()
except:
    clean_up()  

Pros and cons of LBYL vs EAFP

The advantages and disadvantages of one style or the other will vary greatly depending on our code, the way the language handles errors, or even personal preference.

In general, LBYL allows us to see more clearly the necessary conditions that must be met for actions to be executed, making the code more explicit. It also allows us to avoid the uncontrolled errors that can occur when executing the code directly using the EAFP method. And on the other hand, the performance may not be as good because it requires checks. In addition, with LBYL you can introduce race conditions where the condition changes value between the time of checking and the time the code is executed.

As for EAFP, you could say that although the code is not as explicit, it is more concise and cleaner when you try the operation directly. And unlike LBYL, it can have better performance by not relying on checks, and especially in cases where that check would be positive. Furthermore, we also avoid the race conditions that can occur. However, we should be careful if we expect a lot of exceptions, which can make the code less readable and more difficult to debug.

When to use LBYL or EAFP

The choice between using LBYL (Look Before You Leap) and EAFP (Easier to Ask for Forgiveness than Permission) depends on several factors including the specific situation, the potential risks involved, and the readability/maintainability of the code.

In the case of Python, the EAFP coding style is pretty popular and common and it’s usually recommended over the LBYL style.

That’s because exception handling is fast and efficient in Python, and that the necessary checks for potential problems are typically part of the language itself.

What about you? Do you use more LBYL or EAFP?