Glossary

EAFP

Also known as: Easier to Ask Forgiveness than Permission

EAFP (Easier to Ask Forgiveness than Permission) is a Python coding style that assumes an operation will succeed and handles the exception if it doesn't, rather than checking preconditions in advance. The contrasting style is LBYL (Look Before You Leap), which checks conditions before attempting the operation.

A classic example: rather than checking if key in dictionary: before accessing dictionary[key] (LBYL), the EAFP approach simply wraps dictionary[key] in a try/except KeyError block. EAFP is generally considered more Pythonic for several reasons: it avoids race conditions (the condition might change between the check and the operation), it is often faster when the common case is success (no redundant check), and it reads naturally in a language with clean exception handling.

EAFP is not universally appropriate. If the "exceptional" case is actually the common case, the overhead of creating and catching exception objects can make EAFP slower than a simple if check. The choice between EAFP and LBYL is pragmatic, not dogmatic — but EAFP is the default instinct in Python culture, and much of the standard library is designed around it.

Related terms: LBYL, Exception, Try/Except

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.