Skip to main content

Pythonic Error Handling

EAFP vs LBYL

0:00
LearnStep 1/3

The Pythonic Way: EAFP

In Python, you will often hear the mantra EAFP: It's Easier to Ask Forgiveness than Permission. This contrasts with the LBYL (Look Before You Leap) style common in languages like C or Java.

LBYL: Look Before You Leap

In LBYL, you explicitly test for pre-conditions before making a call or lookups. This style emphasizes safety checks.

python

EAFP: Easier to Ask Forgiveness than Permission

In EAFP, you assume the existence of valid keys or attributes and catch the exception if the assumption proves false. This often results in cleaner, more readable code that focuses on the "happy path".

python

Why EAFP?

  • Race Conditions: LBYL is prone to "Time of Check to Time of Use" (TOCTOU) bugs. For example, checking if a file exists before opening it doesn't guarantee it will still exist milliseconds later when you try to open it. EAFP handles the operation atomically.
  • Performance: If the error is rare, EAFP is generally faster because it avoids the overhead of the check. However, if exceptions are thrown frequently, LBYL can be faster because exception handling in Python has a higher overhead than a simple if check.
  • Readability: EAFP keeps the main logic flow linear without deep nesting of checks.

When to use LBYL?

Use LBYL if the "error" case is expected to happen frequently (making exceptions too costly) or if the check is simple and aids clarity without risking race conditions.