Chapter 10: Input validation

LBYL vs. EAFP

face Josiah Wang

Here is another example.

In LBYL, you check whether an item is a key in my_dict before you append the value of my_dict[item] to value.

1
2
3
for item in items: 
    if item in my_dict: 
        value += my_dict[item]

In EAFP, you just go ahead and append my_dict[item] to value. If a KeyError is raised, then you skip this case.

1
2
3
4
5
for item in items:
    try: 
        value += my_dict[item] 
    except KeyError: 
        pass

In the first version with LBYL, you are trying hard to make sure that a KeyError does not occur in the first place! Thus, the if statement somehow ends up becoming part of your algorithm.

Compare that to the second version with EAFP which just lets KeyError happen (occasionally), so there are no unnecessary if checks to confuse the reader about the main intention of the code (Line 3).