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.

Easy Python 3.9+ Aug 9, 2026 Errors & debugging 14 views 0 copies

Python code

17 lines
Python 3.9+
def 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

stdout
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

  1. Use d.get(key, default) as a more concise alternative to try-except
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Errors & debugging

Related tutorials and quizzes for this topic.