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.
EAFP: try/except around the operation. Pythonic when failure is exceptional.
LBYL: if/else checks before the operation. Clearer when failure is common.
Race conditions: LBYL can fail between check and use in concurrent code. EAFP is atomic if the operation is atomic.
Performance: exceptions are cheap when not raised; LBYL checks are cheap but add code.
Trade-off: EAFP can mask errors if you catch too broadly. Catch specific exceptions.
Common mistake: using EAFP to catch broad Exception and ignore it, hiding bugs.
Common mistake: using LBYL to check file existence before opening, which is a race condition. Use try/except.
Version note: the terms come from Python culture; the behavior is stable across versions.
0-2 years experience
2-5 years experience
5-8 years experience
8+ years experience