Lesson · Idiomatic Python & Code Quality
EAFP vs LBYL
55 min readEAFP vs LBYL
EAFP performs an operation and handles the specific failure, while LBYL checks a condition first. The right choice depends on clarity, cost, and whether a check can become stale before use.
Learning goals
- Write the same default-value logic twice, once with
try/except KeyError(EAFP) and once with anincheck (LBYL), and read the difference in intent. - Explain why EAFP fits Python: operations raise typed exceptions, so the handler can name the exact failure it expects.
- Explain why a pre-check can go stale between the check and the use, and describe a file or mapping scenario where that happens.
- Choose a style from staleness and cost: how expensive the check is, how often the ordinary case succeeds, and which version a reviewer reads faster.
- Justify keeping an
exceptclause narrow instead of catching everything.
Mental model
The styles answer the same question from opposite ends: LBYL asks permission first, EAFP acts and handles the refusal. The deciding factor is not taste but time: a check and the operation it guards are two separate moments, and anything that can change in between turns a passing check into a stale one. When no such gap exists and the check is cheap, both work, so readability decides.
Mental model
read it top to bottom
need a value or an effect ↓ is a reliable pre-check available? LBYL: check first, then act ↓ can the state change between check and act? EAFP: act, then handle the specific exception ↓ either way narrow the handling to the expected failure
Core idea
EAFP and LBYL are two placements of the same knowledge: LBYL states the rule for success before acting, EAFP states the failure it expects after acting. Python leans EAFP because exceptions carry precise types and the ordinary path runs without a guard, but the deciding factors are staleness and cost, not idiom preference: a pre-check that can go out of date is a bug, while an exception handler that catches everything hides bugs of its own.
Easier to Ask Forgiveness than Permission
EAFP (Easier to Ask Forgiveness than Permission) attempts the operation first and handles the specific exception if it fails, so the ordinary path runs without a guard. In Python this is the natural shape because failures arrive as typed exceptions: try: timeout = mapping["timeout"] with except KeyError: reads as one attempt plus one report. The handler must name the expected failure; catching everything converts real bugs into fallbacks.
Look Before You Leap
LBYL (Look Before You Leap) checks a condition first and performs the operation only when the check passes, as in if "timeout" in mapping:. It reads clearly when the check is cheap and the state cannot change between the two moments, such as local values the same thread owns. Its weakness is that gap: the check and the operation are separate events, so external or concurrent state can invalidate the check before the operation runs.
Race conditions between check/use
A check/use race is a stale pre-check: the condition is tested at one moment and the operation relies on it at another, and the state changes in between. In single-process code this shows up around files, sockets, and shared caches, for example if path.exists() followed by a read that raises FileNotFoundError because another process removed the file. EAFP removes the window by letting the operation report its own failure instead of trusting an earlier snapshot.
Choosing the clearer approach
Choosing between EAFP and LBYL is a decision about the failure, not a matter of style: how expensive the check is, how often the ordinary case succeeds, and whether the check can go stale before the operation runs. When a stable, cheap check exists, LBYL states the condition explicitly; when the state is external or the operation's exception is already precise, EAFP keeps the common path clean. The tie-breaker is the reader: pick the version whose failure behavior is visible without tracing two separate moments.
Walkthrough
- The EAFP branch goes straight for the value:
mapping["timeout"]succeeds and binds 5, while theexcept KeyErrorclause supplies the fallback 30 only when the subscription fails. The handler names the one failure it expects. - The LBYL branch asks
"timeout" in mappingfirst, then repeats the same subscript inside theif; with the key present, both paths end attimeout_again = 5, but the lookup now happens twice on the ordinary path. - The styles agree here because a plain dict cannot change between the
incheck and the subscription, which is exactly when the choice falls back to readability. Give the mapping behavior that can change between those two moments, such as a live cache another thread edits, and the LBYL pair splits into a check and a use that no longer agree. - Predict before running: what
timeoutandtimeout_againprint for this input, and which exception each version would surface if the key were missing and its fallback branch removed (EAFP re-raisesKeyError, while LBYL leavestimeout_againunbound).
Experiments to try
- Remove
"timeout"frommappingand rerun; both variables become 30, and theexcept KeyErrorfires only in the first block. Record which lines run in each style. - Change the handler to
except TypeErrorand rerun with the key absent; observe the uncaughtKeyErrorand use it to argue for naming the expected failure. - Build a one-off
dictsubclass whose__contains__returnsTruewhile__getitem__raisesKeyError, then run both styles against it: LBYL fails on the subscription, EAFP falls back cleanly. - Replace the EAFP block with
mapping.get("timeout", 30)and compare the three versions for line count, clarity, and behavior when the key is present.
Common mistakes
- Catching broadly to make EAFP work:
except Exceptionalso swallows the bugs you needed to see, so the handler must name the failure it expects, such asKeyError, and let everything else propagate. - Using
try/exceptfor ordinary control flow where a stable check is free: for a dict default,mapping.get("timeout", 30)states the intent in one expression, and wrapping a subscription in a handler adds machinery without adding clarity. - Keeping LBYL where the state can change:
if path.exists(): data = path.read_text()still fails because another process can remove the file between the check and the read, and the mechanism is the gap between the two moments. - Assuming EAFP is always the faster choice: raising and catching an exception costs more than a lookup guard, so in a loop where failures are the common case, the pre-check can be the cheaper style.
Practice: Easy
- Delete
"timeout"frommapping, rerun the worked example, and record which branch of each style runs and the final value of both variables. - Change
except KeyErrortoexcept TypeErrorand rerun with the key absent; record the uncaught exception and state in one sentence why the handler must name the expected failure. - Rewrite the EAFP block as
timeout = mapping.get("timeout", 30)and compare the three versions for line count, readability, and behavior on a present key.
Practice: Medium
- Write
read_config(path)twice, once LBYL withif path.exists(): return path.read_text()and once EAFP withtry: return path.read_text()/except FileNotFoundError: return None; describe a scenario where the LBYL version fails despite a passing check. - Build the stale-check demo: a
dictsubclass whose__contains__returnsTruewhile__getitem__raisesKeyError; run both styles against it and explain which one survives and why. - Take a loop that reads 1,000 keys where all but one are present and time the EAFP and LBYL versions with
time.perf_counter; state which cost dominates in each and when you would switch styles.
Practice: Hard
- Build
read_json(path)with EAFP: catchFileNotFoundError(returnNone) andjson.JSONDecodeError(raiseValueErrorwith the path and the error position) as separate handlers; test both failure paths plus a success. - Build a check/use race lab with two threads or processes, one checking existence and one removing the file in between; capture the LBYL failure with evidence, fix it in EAFP form, and explain which interleaving produced the original failure.
- Write a team decision rule for EAFP vs LBYL: when LBYL wins (cheap, stable check on local state), when EAFP wins (external or concurrent state, precise exception available), and which pitfalls (stale checks, broad handlers) the rule must prevent; test it against three functions from this module.
Lesson checklist
- I can write the same default-value logic in EAFP and LBYL forms and say which one reads faster.
- I can explain why a pre-check can be stale and give one file or mapping example.
- I can name the specific exception my handler expects and justify keeping it narrow.
- I can choose a style based on cost and staleness rather than habit.
Remember
EAFP and LBYL place the same knowledge at different moments: one after the attempt, one before it. Use the pre-check when it is cheap and cannot go stale, use the operation's own exception when state is external or concurrent, and keep both narrow: the check must test the real condition, and the handler must name the failure it expects.
Interview angles
What is the main purpose of **Easier to Ask Forgiveness than Permission**?+
EAFP attempts the operation directly and handles the specific failure afterward: timeout = mapping["timeout"] inside try, with except KeyError supplying the fallback. The ordinary path runs without a guard, and the handler names the failure it expects.
What should you pay attention to when using **Look Before You Leap**?+
LBYL checks a condition first and acts only when it passes, as in if "timeout" in mapping:. It reads well when the check is cheap and cannot go stale, but the check and the operation are two separate moments, so state that changes between them turns a passing check into a wrong answer.
How does **Race conditions between check/use** fit into this lesson?+
A check/use race happens when the state verified by a pre-check changes before the operation that relied on it, for example a file removed after Path.exists() returned True or a key deleted after an in test. EAFP removes the window by treating the operation's own exception as the report.
Why can `except Exception` defeat the purpose of EAFP?+
The handler decides which failures become ordinary outcomes: catching Exception also swallows unrelated bugs, such as a mistake inside the fallback code, and turns them into the default value. EAFP keeps its intent only when the except names the specific failure it expects, such as KeyError.