Skip to content
This repository has been archived by the owner on May 16, 2024. It is now read-only.

Python Control Flow: EAFP Vs LBYL #1

Open
scarecrow1123 opened this issue Apr 21, 2019 · 0 comments
Open

Python Control Flow: EAFP Vs LBYL #1

scarecrow1123 opened this issue Apr 21, 2019 · 0 comments
Labels

Comments

@scarecrow1123
Copy link
Owner

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

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests

1 participant