Python EAFP: Ask Forgiveness First
EAFP means try the thing first, then handle the miss. The letters stand for easier to ask forgiveness than permission.
Check first, then look up
The if line checks for Bob first. The else line prints when he is missing.
ages = {"Ada": 30}
name = "Bob"
if name in ages:
print(ages[name])
else:
print("No age")Try first, then handle the miss
The try line looks Bob up at once. The except line prints when he is missing.
ages = {"Ada": 30}
try:
print(ages["Bob"])
except KeyError:
print("No age")EAFP with a list index
Index 5 is past the end. The except line prints a plain line.
nums = [10, 20, 30]
try:
print(nums[5])
except IndexError:
print("Too far")EAFP when the key is there
The key Ada is there. The try line prints her age at once.
ages = {"Ada": 30}
try:
print(ages["Ada"])
except KeyError:
print("No age")Example
ages = {"Ada": 30, "Cy": 25}
found = 0
for name in ["Ada", "Bob", "Cy", "Dee"]:
try:
print(name, ages[name])
found = found + 1
except KeyError:
print(name, "is missing")
print("Found:", found)Key points
- EAFP: try the thing first, then handle the miss
- Use try to attempt the lookup at once
- Use except to handle the miss when it happens
- Checking first looks at the key twice
- EAFP looks once, so the code stays short
- Use EAFP when the lookup usually works
In this example, ages holds two names. The loop tries four names in turn. Ada and Cy print with their ages. Bob and Dee print as missing. The count of 2 proves two lookups worked.
Note
EAFP is the usual Python style.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does EAFP code do first?