Graham Knapp

Result pattern - An exceptional way to handle errors

written by Graham Knapp on 2024-12-30

People often say that in Python you should use exceptions - "Easier to Ask Forgiveness than Permission" (EAFP) over guard clauses - "Look Before You Leap" (LBYL), but the Result design pattern - returning an object which explicitly states whether the operation succeeded is a useful alternative where error handling is required and, as I learned by exploring in more depth, it can be compatible with both approaches.

As my design patterns repo approaches 100⭐ on GitHub I decided to add the Result design pattern to the mix

EAFP vs LBYL

or Graham plays with GitHub Code Search

Prompted by a post on Mastodon I looked a bit more into which patterns people are using for error handling specifically for attribute lookup: I'm surprised to see twice as many references to hasattr as for "except AttributeError"

and not only for dynamic lookups but also for general attribute search, so a win for LBYL vs EAFP style with Python, despite the latter often being recommended ?