Also known as: Look Before You Leap
LBYL (Look Before You Leap) is a coding style that checks preconditions before attempting an operation. For example, checking if key in dictionary: before accessing dictionary[key], or if os.path.exists(path): before opening a file. This contrasts with the EAFP (Easier to Ask Forgiveness than Permission) style, which attempts the operation and catches any exception.
LBYL is the dominant style in languages like C and Java, where exception handling is expensive or cumbersome. In Python, LBYL is less favoured because of a subtle problem: between the check and the operation, conditions can change (a "time of check to time of use" or TOCTOU race condition). A file can be deleted between the exists() check and the open() call. A dictionary can be modified by another thread between if key in d and d[key].
That said, LBYL has its place. When the check is cheap and the failure case is common (not exceptional), LBYL can be faster and clearer than setting up a try/except block. isinstance() checks before type-specific operations, hasattr() before attribute access, and if items: before iterating are all common LBYL patterns that are perfectly Pythonic when used judiciously.
Discussed in:
- Chapter 11: Error Handling — EAFP vs LBYL