Python dict try-except KeyError EAFP vs LBYL
Compare EAFP (try-except) and LBYL (if-in-check) styles for safely accessing dictionary keys, with working examples in Python.
Python code
17 linesdef safe_get_lbyl(d, key):
if key in d:
return d[key]
return "default-lbyl"
def safe_get_eafp(d, key):
try:
return d[key]
except KeyError:
return "default-eafp"
if __name__ == "__main__":
data = {"name": "Alice", "age": 30}
print("LBYL:", safe_get_lbyl(data, "missing"))
print("EAFP:", safe_get_eafp(data, "missing"))
print("LBYL existing:", safe_get_lbyl(data, "name"))
print("EAFP existing:", safe_get_eafp(data, "name"))
Output
LBYL: default-lbyl
EAFP: default-eafp
LBYL existing: Alice
EAFP existing: Alice
How it works
The code defines two functions safe_get_lbyl and safe_get_eafp that each return a default value when a key is missing from a dictionary. safe_get_lbyl uses LBYL (Look Before You Leap) by checking if key in d before accessing the key, while safe_get_eafp uses EAFP (Easier to Ask for Forgiveness than Permission) by attempting the access directly inside a try block and catching KeyError. Both approaches produce identical output for missing and existing keys. EAFP is often preferred in Python because it avoids double lookup and is more idiomatic in concurrent scenarios, though LBYL can be clearer in simple cases.
Common mistakes
- Catching too broad an exception (e.g., Exception) instead of KeyError, which may hide bugs
- Assuming dict access always raises KeyError for missing keys, but using 'default' with .get can be simpler
- Forgetting that EAFP can also catch IndexError for lists, so pick the right exception type
- In LBYL, checking 'key in d' is a separate step that may be inconsistent with the subsequent access
Variations
- Use d.get(key, default) as a more concise alternative to try-except
- Use collections.defaultdict or a custom dict subclass to supply defaults automatically
Real-world use cases
- Configuration parsing where optional keys may be absent from user-provided dictionaries.
- Data cleaning pipelines that must gracefully handle missing fields in incoming records.
- API response handling where you expect some fields to be optional in JSON payloads.
Sponsored
More from Errors & debugging
- Catch RecursionError and Fail Gracefully in Python easy
- Catch ValueError and print friendly message in Python easy
- Collect Multiple Validation Errors in Python Before Raising medium
- Handle ValueError and ZeroDivisionError in Python with try except easy
- How to Add a Correlation ID to Logging Records in Python medium
- How to Assert Preconditions with Descriptive Messages in Python easy
Keep learning
Related tutorials and quizzes for this topic.