What do EAFP and LBYL mean, and why does idiomatic Python usually favor EAFP?
Answer
LBYL ("look before you leap") checks preconditions before acting, like `if key in d: value = d[key]`. EAFP ("easier to ask forgiveness than permission") just attempts the operation inside a `try` and handles the exception if it fails, like `try: value = d[key] except KeyError: ...`. Python favors EAFP because checking and then acting is not atomic — the state can change between the check and the use in concurrent code, causing a race condition — and because EAFP avoids doing the lookup or validation work twice (once to check, once to use), which is often both simpler and faster in the common case where the operation succeeds.
Strong answer includes
- LBYL checks first, EAFP tries and handles failure
- check-then-act is not atomic, can race under concurrency
- EAFP avoids doing the work twice in the common successful case
Practical example
try:
value = cache[key]
except KeyError:
value = compute_and_store(key)avoids a separate
if key in cache:check that would otherwise race with another thread evicting the key between the check and the read.