Trying First and Handling Failure: EAFP and LBYL in Python

This article compares the EAFP and LBYL styles of Python, measures their cost when an operation succeeds and when it fails, and explains why narrow try blocks and dedicated tools avoid the errors of both.

A close view of a green tree python with yellow-green scales, its head raised beside its thick coils against a dark background
Photo by Oleksandr Sushko on Unsplash

Every operation that may fail raises the same question: should the program check the conditions first, or attempt the operation and handle the failure? The present article addresses the two styles that answer it, which the Python glossary names LBYL, "look before you leap", and EAFP, "easier to ask for forgiveness than permission". It compares them on dictionaries and files, measures their cost when the operation succeeds and when it fails, and analyses the errors that each style produces, from race conditions to except clauses that catch more than intended. Attempting the operation directly and handling only the failure that was expected, so that the common case is written without detours, is the secret weapon of EAFP.

Two Ways to Handle a Possible Failure

LBYL tests the preconditions explicitly before the operation, whereas EAFP assumes that the operation will succeed and catches the exception raised when it does not. The glossary describes EAFP as a common Python style, and the language supports it at every level: even the built-in hasattr is implemented by calling getattr and checking whether it raises AttributeError. For files the difference is not only stylistic, because a check and the following operation are two separate moments, and the file may be deleted or replaced in between.

import os

profile = {"name": "Alice"}

if "age" in profile:          # LBYL: two lookups when the key exists
    print(profile["age"])
else:
    print("age not set")      # Output: age not set

try:                          # EAFP: one lookup in the common case
    print(profile["age"])
except KeyError:
    print("age not set")      # Output: age not set

path = "settings-that-do-not-exist.toml"
print(os.path.exists(path))   # Output: False
try:
    with open(path) as handle:
        text = handle.read()
except FileNotFoundError:
    text = ""
print(repr(text))             # Output: ''

Both dictionary versions print the same result, but the LBYL version searches the dictionary twice whenever the key exists. The file example shows why the check is not enough: os.path.exists answers for one instant, so a program that relies on it can still fail when open runs, and the documentation of os.access describes such a check before opening a file as a security hole. Only the try around open handles every outcome, because the operation and its failure are the same event. The same race appears with dictionaries shared between threads, where another thread may remove a key between the membership test and the lookup.

Measuring Success and Failure

Since Python 3.11, a try statement costs nothing when no exception is raised, but raising and catching an exception remains far more expensive than a membership test. The following measurement compares a missing key under both styles.

import timeit

data = {"name": "Alice", "age": 30}

def lbyl(key):
    if key in data:
        return data[key]
    return None

def eafp(key):
    try:
        return data[key]
    except KeyError:
        return None

miss_lbyl = timeit.timeit(lambda: lbyl("zip"), number=200_000)
miss_eafp = timeit.timeit(lambda: eafp("zip"), number=200_000)
print(miss_eafp > 2 * miss_lbyl)  # Output: True

On CPython 3.12, a present key took about 48 nanoseconds with LBYL and about 40 with EAFP, because EAFP performs one lookup instead of two; a missing key took about 42 nanoseconds with LBYL and about 130 with EAFP, three times as much. The saving on success is therefore small and the penalty on failure large, so EAFP is faster only when failures are rare, below roughly one call in ten by these figures. For dictionaries the question often disappears, because dict.get took about 42 nanoseconds in both cases; when None is itself a valid value, a dedicated marker distinguishes the missing key, as described in the article devoted to the Sentinel pattern.

Friendly Fire: Pitfalls of Both Styles

An except clause catches every exception of its type raised anywhere inside the try block, including those raised by functions called from it, so the most frequent error of EAFP is handling a failure that the code did not anticipate. Six pitfalls are distinguished, which are the following:

  1. Too broad a try block. A KeyError raised by a bug in a called function is caught as if it were the expected missing key.
  2. Bare except or except Exception. Such clauses hide unrelated errors, and a bare except also catches KeyboardInterrupt.
  3. Exceptions as frequent control flow. When failure is common, each exception costs about three times a simple check.
  4. Partial side effects. An operation that fails half-way may already have written data, so EAFP must be combined with cleanup or a transaction.
  5. Checks that race. LBYL on files, shared dictionaries or other external state can be invalidated between the check and the action.
  6. Ignoring dedicated tools. dict.get, dict.setdefault, getattr with a default and contextlib.suppress express the common cases more clearly than an explicit try.

The first pitfall and its correction are reproduced in the following example.

prices = {"apple": 1.2}
discounts = {}

def final_price(item):
    return prices[item] * (1 - discounts[item])  # bug: discount missing

try:
    print(final_price("apple"))
except KeyError:
    print("unknown item")  # Output: unknown item

def safe_price(item):
    try:
        price = prices[item]
    except KeyError:
        return "unknown item"
    else:
        return price * (1 - discounts.get(item, 0))

print(safe_price("apple"), safe_price("pear"))  # Output: 1.2 unknown item

The first version reports an apple as an unknown item, although the apple exists and the real problem is the missing discount; the broad try turned a bug into a wrong but plausible answer. The corrected version keeps only the expected lookup inside try and moves the rest to else, which runs only when no exception was raised. When the only reaction to an exception is to ignore it, contextlib.suppress, described in the article devoted to custom context managers, states that intention in one line.

Choosing a Style

Consequently, neither style is correct in every case; the choice depends on how often the operation fails, whether the check can race and whether a dedicated tool already exists, as the following table summarizes.

Situation Recommended approach
Failure is rare and the operation is a single step EAFP with a narrow try
Failure is frequent and the check is cheap LBYL
Files, sockets or state shared between threads EAFP, because a check can race
A default for a missing key or attribute dict.get, setdefault or getattr with a default
An exception that should simply be ignored contextlib.suppress
An action with irreversible side effects Validate first, then act
Code that must run only after a successful step try, except and else

Conclusion

It is concluded that EAFP attempts an operation and handles the expected exception, whereas LBYL checks the conditions beforehand, that EAFP avoids races and duplicated lookups and costs nothing on success since Python 3.11, and that each failure costs about three times a simple check. This magic depends on keeping the try block narrow and the except clause specific, so that only the anticipated failure is forgiven. Keeping a collection organized so that its smallest element is always available without sorting it completely is the purpose of the heapq module, which is developed in a future article of this series.