Programming Search⌘K

Featurecore

EAFP and LBYL

Also called EAFP, LBYL, easier to ask for forgiveness than permission, look before you leap, check then act, TOCTOU.

EAFP code tries the operation and catches the exception when it fails. LBYL code tests the conditions first with if. A test can go stale before the operation runs, so EAFP is often safer.

Language
Python

Synopsis

config = {"host": "localhost"}

if "port" in config:
    port = config["port"]
else:
    port = 8080

try:
    host = config["host"]
except KeyError:
    host = "0.0.0.0"

print(host, port)
Output
localhost 8080

The if test is LBYL. The try statement is EAFP.

Semantics

r1. EAFP stands for "Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false."1 It "is characterized by the presence of many try and except statements."1

r2. LBYL stands for "Look before you leap. This coding style explicitly tests for pre-conditions before making calls or lookups."1 It "is characterized by the presence of many if statements."1 The glossary calls it "common to many other languages such as C."1

r3. The main risk of LBYL is a race. "In a multi-threaded environment, the LBYL approach can risk introducing a race condition between “the looking” and “the leaping”."1 For example, if key in mapping: return mapping[key] "can fail if another thread removes key from mapping after the test, but before the lookup."1 The fix is a lock or the EAFP style.1 Example: check-then-use.

r4. Files are the common case. The os.access documentation warns that a test before open() "creates a security hole, because the user might exploit the short time interval between checking and opening the file to manipulate it. It’s preferable to use EAFP techniques."2 Example: open-or-default.

r5. EAFP fits duck typing. Duck-typed code "typically employs hasattr() tests or EAFP programming."1 hasattr itself works by "calling getattr(object, name) and seeing whether it raises an AttributeError or not."3 Example: duck.

r6. Keep the try clause small. PEP 8 says to "limit the try clause to the absolute minimum amount of code necessary. Again, this avoids masking bugs".4 Put the code that runs on success in the else clause: it "avoids accidentally catching an exception that wasn’t raised by the code being protected by the try … except statement."5 Catch a named exception, not all of them. Example: broad-try.

r7. Cost: "A try/except block is extremely efficient if no exceptions are raised. Actually catching an exception is expensive."6 So the FAQ says that the try form of a dictionary lookup "only made sense when you expected the dict to have the key almost all the time."6

r8. Some tools remove the choice. dict.get returns a default, "so that this method never raises a KeyError."7 dict.setdefault inserts the default when the key is missing.7 Example: no-test-needed.

Examples

import os
import tempfile


def load(path):
    try:
        f = open(path, encoding="utf-8")
    except FileNotFoundError:
        return "default"
    with f:
        return f.read()


with tempfile.TemporaryDirectory() as folder:
    path = os.path.join(folder, "settings.txt")
    print(load(path))
    with open(path, "w", encoding="utf-8") as f:
        f.write("custom")
    print(load(path))
Output
default
custom

There is no time between a test and the open, because there is no test (rule r4). The try clause holds only the open call, and the with block reads the file after it (rule r6).

import io


def read_all(source):
    try:
        read = source.read
    except AttributeError:
        return str(source)
    return read()


print(read_all(io.StringIO("from a file")), read_all(42))
Output
from a file 42

The function does not ask for a type. It tries the attribute read, and it falls back when the object has none (rule r5). The call read() is outside the try, so an AttributeError inside read is not hidden.

from collections import defaultdict

counts = {}
for word in "a b a c a".split():
    counts[word] = counts.get(word, 0) + 1
print(counts)

groups = defaultdict(list)
for word in ["apple", "avocado", "banana"]:
    groups[word[0]].append(word)
print(dict(groups))
Output
{'a': 3, 'b': 1, 'c': 1}
{'a': ['apple', 'avocado'], 'b': ['banana']}

get and defaultdict need neither an if nor a try (rule r8).

Versions

Since 3.11

"“Zero-cost” exceptions are implemented, eliminating the cost of try statements when no exception is raised."8 So a try statement costs almost nothing when no exception is raised, and the EAFP style is cheap on the success path.

Pitfalls

This code raises KeyError, on purpose.

cache = {"k": 1}


def other_thread():
    cache.pop("k", None)


def lookup(key):
    if key in cache:
        other_thread()
        return cache[key]
    return None


print(lookup("k"))

The call other_thread() stands for another thread that runs between the test and the lookup. The test said yes, but the key is gone when the lookup runs (rule r3). With real threads, the failure is rare and hard to reproduce. Write try: return cache[key] with except KeyError, or use cache.get(key).

This code runs but gives a wrong answer on purpose.

for text in ["42", "-5", " 7 ", "²"]:
    print(repr(text), text.isdigit(), end=" ")
    try:
        print(int(text))
    except ValueError:
        print("ValueError")
Output
'42' True 42
'-5' False -5
' 7 ' False 7
'²' True ValueError

A test can disagree with the operation. isdigit is false for -5 and for 7, but int accepts both. isdigit is true for the superscript two, because digits include "the compatibility superscript digits", but int rejects it.7 The only exact test for int(text) is to call it.

This code runs but gives a wrong answer on purpose.

def handle(value):
    return value["name"]


def show(record, key):
    try:
        return handle(record[key])
    except KeyError:
        return "missing key"


print(show({"user": {"id": 1}}, "user"))
Output
missing key

The key user is there. The KeyError came from handle, but the handler reports a missing key. PEP 8 shows the fix: look up the key in the try clause, and call handle in the else clause (rule r6).

Comparison

Both styles are correct when nothing changes between the test and the act, and when the test checks exactly what the act needs. LBYL reads better when failure is common, because catching an exception is slower than an if test (rule r7). EAFP is safer with files, threads and other shared state. For the try statement itself, see Handling Exceptions. For locks, see Thread synchronization.

References

  1. Glossary, Python 3.15 documentation, duck-typing; EAFP; LBYL
  2. os, Miscellaneous operating system interfaces, Python 3.15 documentation, os.access(), Note
  3. Built-in Functions, Python 3.15 documentation, hasattr()
  4. PEP 8, Style Guide for Python Code, Programming Recommendations
  5. The Python Tutorial, Python 3.15 documentation, 8.3 Handling Exceptions
  6. Design and History FAQ, Python 3.15 documentation, How fast are exceptions?
  7. Built-in Types, Python 3.15 documentation, Mapping Types, dict.get(); dict.setdefault(); str.isdigit()
  8. What’s New In Python 3.11, Faster CPython, Misc

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source