Show Menu
Cheatography

LBYL or EAFP - How to deal with errors in Python? Cheat Sheet (DRAFT) by

Look before you leap (LBYL), and easier to ask forgiveness than permission (EAFP) are two strategies on how to deal with exceptions and errors (or avoid them!) in Python. They are not exclusive to Python, but these names are popular in the community.

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Defini­tions

Look Before you Leap is a coding style more common in other languages. The main charac­ter­istic is the presence of condit­ional statem­ents, or if statem­ents. The idea is to include explicit statem­ents, before calls, to make sure the call is going to be valid.
Easier to Ask Forgiv­eness than Permission in contrast is more pythonic. It is charac­terized by try and except statem­ents, assuming that keys and attributes are valid and handling the exceptions in the except block. It seems to be more optimized in Python than the altern­ative.

Deciding wich one to use

 

What do they look like

Criteria
LBYL
EAFP
Clear or easy to read
It's more difficult to read and sometimes puts checks in the spotligh instead of the actual purpose of the code. The exceptions may look more important than the rule.
The purpose is clear and in the foregr­ound, while exceptions come after and are dealt with. Reads more clear and straig­htf­orward.
Can it cause a race condition?
It's possible. The operation comes after the check, if a key or attribute is removed between the condition and the call, an exception can happen.
Race conditions are prevented since it is assumed that the operation is valid and the exception is dealt with if not.
Perfor­mance
Performs better when the checks mostly fail, and worse when the checks mostly succeed.
If the checks fail a lot, it performs worse. Performs better if more successful operations happen.