04 / 05

Why is "EAFP" (Easier to Ask Forgiveness than Permission) considered more Pythonic than "LBYL" (Look Before You Leap)?

Difficulty: 6/10
EAFP, LBYL, Exception Handling, Idiomatic Style

EAFP: try the operation and handle exceptions; LBYL: check preconditions first

EAFP means you attempt the operation and catch exceptions if it fails. LBYL means you check conditions before attempting the operation. Python favors EAFP because it avoids race conditions between the check and the use, and because exceptions are cheap when they are not raised. For example, try: value = d[key] except KeyError: ... instead of if key in d: value = d[key] else: ... EAFP also works better with duck typing: you try to use an object and handle AttributeError if it does not support the operation. However, LBYL can be clearer for simple checks and avoids exception overhead when failures are frequent. The rule of thumb is to use EAFP for exceptional cases and LBYL for expected control flow.

  1. 1

    EAFP: try/except around the operation. Pythonic when failure is exceptional.

  2. 2

    LBYL: if/else checks before the operation. Clearer when failure is common.

  3. 3

    Race conditions: LBYL can fail between check and use in concurrent code. EAFP is atomic if the operation is atomic.

  4. 4

    Performance: exceptions are cheap when not raised; LBYL checks are cheap but add code.

  5. 5

    Trade-off: EAFP can mask errors if you catch too broadly. Catch specific exceptions.

  6. 6

    Common mistake: using EAFP to catch broad Exception and ignore it, hiding bugs.

  7. 7

    Common mistake: using LBYL to check file existence before opening, which is a race condition. Use try/except.

  8. 8

    Version note: the terms come from Python culture; the behavior is stable across versions.

javascript

Scenario Questions

0-2 years experience

  1. 1What is the difference between 'if key in d' and 'try: d[key] except KeyError'?
  2. 2Why is checking file existence before opening a race condition?

2-5 years experience

  1. 1You need to parse user input that is usually valid but sometimes not. Which approach do you use and why?
  2. 2You are catching a broad Exception in an EAFP block. How do you narrow it?

5-8 years experience

  1. 1You are writing a library and want to support duck typing. How does EAFP help?
  2. 2You have a hot loop where failures are common. Should you use EAFP or LBYL? Why?

8+ years experience

  1. 1Design an API that uses EAFP consistently and explain how you document the exceptions it raises.
  2. 2Compare EAFP and LBYL on performance, readability, and correctness in concurrent and distributed systems.

Follow-up Questions

  • When would LBYL be more appropriate than EAFP?
  • How does EAFP interact with duck typing?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.