Skip to main content

python-errors-prevent-vs-handle-style-lbyl-vs-eafp

#post

Preventing vs Handling Errors in Python

I keep seeing feedback that it’s not Pythonic to validate invariants before trying an operation (i.e. LBYL, look before you leap, tiger style, guard clauses). That it’s more Pythonic to just try and then handle anything that goes wrong (i.e. EAFP, easier to ask forgiveness than permission).

Intuitively, I look before I leap. And I find defensive programming styles like Tiger Style appealing.

So what’s the deal, Pythonistas? Why so reckless? Why do you want to waste CPU time running that code that may be destined to fail?

Benefits of EAFP (try/except) imo:

  • you can potentially make your code more informative by identifying the exact errors that are possible to encounter
    • e.g. except KeyError is at least as informative is if "key" in dict:
  • your code will run fast if it takes the happy path more often than the error path (by not having to run the guard condition logic)

Downsides of EAFP imo:

  • try/except always indents your code, while guards don’t need to if you return early and keep the happy path on left

Why should the language you’re using dictate your coding style?

Stuff to read: