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
ifbefore acting; EAFP ("easier to ask for forgiveness than permission") just performs the operation and handles the specific exception withtry/except - Correctness: a check and the operation can disagree (
"Β²".isdigit()is true butint("Β²")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;
hasattritself works by callinggetattrand catchingAttributeError - Cost: entering
tryis nearly free in CPython 3.11+, but raising and catching is several times slower than anif, so LBYL (ordict.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
tryblocks 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.