Skip to the solution
MediumDSA10 min read

What is EAFP vs LBYL in Python?

90 views

The problem

Question presented to candidate: "People say Python prefers 'easier to ask forgiveness than permission'. What do EAFP and LBYL mean, why is EAFP considered Pythonic, and are there cases where you would still check first?"

What a strong answer should cover:

  • LBYL ("look before you leap") tests preconditions with if before acting; EAFP ("easier to ask for forgiveness than permission") just performs the operation and handles the specific exception with try/except
  • Correctness: a check and the operation can disagree ("Β²".isdigit() is true but int("Β²") fails), and between a check and the use the world can change (time-of-check to time-of-use races on files, or dict keys across threads, as the Python glossary notes)
  • EAFP fits duck typing: try the operation instead of testing the type; hasattr itself works by calling getattr and catching AttributeError
  • Cost: entering try is nearly free in CPython 3.11+, but raising and catching is several times slower than an if, so LBYL (or dict.get) wins when failure is the common case
  • When LBYL is right: validating all user input up front, avoiding partial side effects, and conditions that are cheap and cannot change; keep EAFP try blocks to the single failing line

Code / implementation expected: Optional β€” the same lookup or file read written both ways, with the race or the edge case that breaks the LBYL version.

  • eafp
  • lbyl

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read Β· 10 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonParsing, dict lookups, duck typing and hasattr: EAFP vs LBYL
PythonCheck-then-use races with files, atomic create, and a too-wide try

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 112 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

What is pickling and what are its risks?

Continue