What is the difference between EAFP and LBYL in Python?
LBYL (look before you leap) checks conditions first, like if key in d. EAFP (easier to ask forgiveness than permission) just tries the operation and handles the exception. Python code usually prefers EAFP, especially where checking and acting could race.
Explain it simply
Before crossing a road, a careful person looks both ways (LBYL). A confident Mumbai commuter just starts walking and reacts if a vehicle appears (EAFP). In Python, trying and catching is often shorter, and avoids a gap in which the situation changes between the check and the action.
Example
data = {"name": "Asha"}
# LBYL
if "age" in data:
age = data["age"]
else:
age = 0
# EAFP
try:
age2 = data["age"]
except KeyError:
age2 = 0
print(age, age2) # Output: 0 0
# Often the cleanest: use the API built for it
print(data.get("age", 0)) # Output: 0A file check shows the race: if os.path.exists(p): open(p) can still fail if another process deletes the file in between. try: open(p) cannot have that problem.
What to say in the interview
"LBYL tests first; EAFP tries and catches. EAFP is the Pythonic style and avoids race conditions between check and use. It is not always best: when failure is common, exceptions are slower than a simple if, and sometimes a built-in like dict.get is the cleanest of all."