Skip to content

EAFP

EAFP stands for easier to ask for forgiveness than permission, a coding style that’s commonly used in Python. The idea behind EAFP is to write code that assumes the existence of valid keys, indices, attributes, or methods, and handles exceptions if they aren’t present. This style contrasts with LBYL, or look before you leap, which is common in languages like C. EAFP code is marked by frequent use of try and except statements.

EAFP aligns with Python’s design philosophy of simplicity and readability. By using EAFP, you can often write more concise and efficient code, as it minimizes the need for explicit checks and relies on Python’s built-in exception-handling mechanisms instead.

In practice, an example of using EAFP would be that instead of checking if a file exists before trying to open it, you go ahead and try to open it, catching the exception if it doesn’t exist. This approach can lead to cleaner code, especially in environments where race conditions might make pre-checks unreliable.

Python’s rich set of exceptions facilitates using EAFP in your code, allowing you to handle errors gracefully and keeping your codebase clean and manageable.

Example

Here’s an example demonstrating the EAFP style in action:

Language: Python
>>> try:
...     with open("example.txt", mode="r") as file:
...         content = file.read()
... except FileNotFoundError:
...     print("The file does not exist.")
...
The file does not exist.

In this example, you try to open example.txt and read from it. You don’t check whether the file exists. Instead, you stick to the EAFP style by catching the FileNotFoundError exception to handle the case of a non-existent file.

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. 21, 2026 • Reviewed by Dan Bader