Skip to content

Instantly share code, notes, and snippets.

@jacksmith15
Last active April 22, 2020 20:21
Show Gist options
  • Save jacksmith15/390ca7bc2a6645a65049fd13aa893c2a to your computer and use it in GitHub Desktop.
Save jacksmith15/390ca7bc2a6645a65049fd13aa893c2a to your computer and use it in GitHub Desktop.

EAFP vs LBYL

This illustrates the difference between EAFP (Easier to ask forgiveness than permission) vs LBYL (Look before you leap).

To illustrate, consider a function which gets a value from a dictionary by key, returning a default if not present. This is the function implemented in each style:

Look before you leap:

def get(dictionary, key, default):
    if key in dictionary:
        return dictionary[key]
    return default

Easier to ask forgiveness

def get(dictionary, key, default):
    try:
        return dictionary[key]
    except KeyError:
        return default

The difference is fairly arbitrary, and yet there is a general consensus for EAFP. I think this is a manifestation of the Zen of Python:

There should be one-- and preferably only one --obvious way to do it

The underlying idea is that it doesn't matter which is better, so long as we pick one and stick to it (i.e. bike-shedding is worse than picking a marginally inferior option).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment