blog
blog copied to clipboard
Python Control Flow: EAFP Vs LBYL
EAFP - Easier to Ask for Forgiveness than Permission LBYL - Look Before You Leap
These are two different ways to do control flow. LBYL style pertains to writing if/else
blocks to make decisions. According to [1], in this not so standard Pythonic way of doing control flow, exceptional cases get the emphasis by the way the conditions are expressed. A common example as below:
if "key" in dict_:
value += dict_["key"]
As [1] suggests, in simpler words, the above piece of code conveys the special case in an emphasized way rather than showing us what is normal. Using try/except
blocks(EAFP), we write what is normal and handle exceptions that may rise out of it. This becomes easier to convey the more natural cases as follows:
try:
value += dict_["key"]
except KeyError:
pass
[2] adds another important case where EAFP helps to avoid race conditions. In a multi-threaded environment, in the above if/else
block, assume a thread has passed the if
condition. Before the next statement gets executed in the current thread, another thread may inadvertently remove the key
from dict_
which would cause an exception in the original thread. However, in the try/except
case, this cannot happen. Another way to solve this problem is to use standard locking mechanisms.
[1] - Idiomatic Python: EAFP versus LBYL
[2] - Chapter 15. Context Managers and else Blocks, Fluent Python, Luciano Ramalho