Cheatography
https://cheatography.com
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.
Definitions
Look Before you Leap is a coding style more common in other languages. The main characteristic is the presence of conditional statements, or if statements. The idea is to include explicit statements, before calls, to make sure the call is going to be valid. |
Easier to Ask Forgiveness than Permission in contrast is more pythonic. It is characterized by try and except statements, 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 alternative. |
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 foreground, while exceptions come after and are dealt with. Reads more clear and straightforward. |
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. |
Performance |
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. |
|