You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository has been archived by the owner on May 16, 2024. It is now read-only.
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.
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: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:[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 theif
condition. Before the next statement gets executed in the current thread, another thread may inadvertently remove thekey
fromdict_
which would cause an exception in the original thread. However, in thetry/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
The text was updated successfully, but these errors were encountered: