Part 06 / Topic 8 of 10
EAFP vs LBYL
Two styles of handling a possible problem:
- LBYL = "Look Before You Leap": check first with
if. - EAFP = "Easier to Ask Forgiveness than Permission": just try it, and catch the error.
Python code usually prefers EAFP. It is short and handles cases you did not think of.
Real-world example: get the stock of a product.
stock = {"pen": 40, "notebook": 12}
# LBYL: check first
def get_stock_lbyl(item):
if item in stock:
return stock[item]
return 0
# EAFP: try, then handle
def get_stock_eafp(item):
try:
return stock[item]
except KeyError:
return 0
print(get_stock_lbyl("pen"), get_stock_lbyl("eraser")) # 40 0
print(get_stock_eafp("pen"), get_stock_eafp("eraser")) # 40 0
| LBYL | EAFP | |
|---|---|---|
| Style | if check first |
try / except |
| Good for | Simple, cheap checks | Many things that can go wrong (files, input) |
| Python's usual choice | Sometimes | Most of the time |
For a dict, stock.get(item, 0) is the simplest of all. Use it when you can.
Full program: examples/05_eafp_vs_lbyl.py.
๐ Going deeper: LBYL can be wrong when things change between the check and the action. A file can be deleted right after
if path.exists():. With EAFP there is no gap, because the action itself is the check.
Done here? The practice set for Part 6 โ 7 exercises with solutions โ is on the part page.