Skip to content

LBYL

LBYL, or look before you leap, is a coding style that emphasizes checking for conditions before executing a particular action. In Python, this often means performing explicit checks to ensure that an operation can be safely executed. This style contrasts with EAFP, or easier to ask for forgiveness than permission, which is more idiomatic in Python. LBYL code is characterized by the presence of many if statements.

LBYL can be useful when you want to avoid exceptions and ensure that your code runs smoothly by validating conditions upfront. However, it can sometimes lead to more verbose and less Pythonic code.

In a multi-threaded environment, LBYL can also introduce a race condition between the check and the action. Another thread may invalidate the condition after you test it but before you act on it. You can solve that with a lock or by switching to the EAFP style.

When using LBYL, you typically use conditional statements to verify that the conditions are suitable for an operation. This approach is often used when dealing with situations where exceptions are costly, or where conditions can be easily checked without performance penalties.

Example

Here’s an example of the LBYL approach in action:

Language: Python
>>> likes = {"pet": "dog", "color": "blue", "fruit": "apple"}
>>> key = "pet"

>>> if key in likes:
...     print(f"Your favorite {key} is {likes[key]}")
... else:
...     print(f"You don't have a favorite {key}")
...
Your favorite pet is dog

This example checks whether the key exists in the dictionary before attempting to access it. This prevents KeyError exceptions and allows you to handle the situation gracefully.

LBYL vs EAFP: Preventing or Handling Errors in Python

Tutorial

LBYL vs EAFP: Preventing or Handling Errors in Python

Choose your Python coding style: look before you leap (LBYL) vs easier to ask forgiveness than permission (EAFP). See clear pros, cons, and examples.

intermediate best-practices python

For additional information on related topics, take a look at the following resources:

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Leodanis Pozo Ramos • Updated Sept. 26, 2026 • Reviewed by Dan Bader