Easier to Ask for Forgiveness than Permission :  A tale of Python’s eccentricity

There’s an old joke that goes something like this — A man fervently begged god for a bike. Even after years of propitiation, nothing was heard from the other side. So, the man stole a bike and then asked god for forgiveness.

I doubt some Computer Scientist created a programming principle based on a joke but you never know. EAFP, short for: Easier to Ask for Forgiveness than Permission, is a programming principle that follows a similar line of reasoning stated in the joke above. As crude as the principle may sound in the real world, computers don’t care about morals. They don’t have feel feelings either (YET!). So, we can safely follow this principle without triggering an apocalypse.

Before we dive into the details, let’s look at an analogy that might make it easier to understand the technicalities later.

Always remember that it’s much easier to apologize than to get permission. In this world of computers, the best thing to do is to do it.” — Grace Hopper

Think before you act, Look before you leap

Let’s assume we are using a dictionary in our python program and we need to modify the value associated with a key. In the standard scenario, the first thing we need to do is check if the key even exists. If someone somewhere has already wiped that key off the dictionary our program would terminate abruptly with a KeyError exception.

test_dict = {}
keys = [1,2,3,4]
values = ['a', 'b', 'c', 'd']


# the for loop will generate this dictionary -> {1:'a', 2:'b', 3:'c', 4:'d'}

for key, value in zip(keys, values):
  test_dict[key] = value  
  

# Now assume you wish to append an 'e' to the pre-existing value associated with key 4

if 4 in test_dict:
  test_dict[4] += 'e'

Before we modify the value associated with the Key 4, we use a conditional statement to verify if the key exists in the dictionary. This is called the LBYL principle, short for Look Before You Leap. Most of us are used to this style of coding.

Living Dangerously

Some of us are iconoclasts. Conventions are just not our thing. I presume that was the case with the developers of Python as well. They had already decided to challenge the conventions by introducing indentation for code blocks, replacing the standard approach of curly braces followed by most programming languages. I wonder if EAFP was supposed to be the cherry on top of the Python pudding.

test_dict = {}
keys = [1,2,3,4]
values = ['a', 'b', 'c', 'd']


# the for loop will generate this dictionary -> {1:'a', 2:'b', 3:'c', 4:'d'}

for key, value in zip(keys, values):
  test_dict[key] = value  
  

# Now assume you wish to append an 'e' to the pre-existing value associated with key 4

try:
  test_dict[4] += 'e'
except KeyError:
  print('The key you are trying to modify does not exist')

Here, everything looks similar to the first gist except for a slightly different approach towards the end. In this case, we don’t verify if the key exists. We jump right in and try to modify the value associated with the key. If the key does not exist, a KeyError exception will be thrown which we handle as needed.

A race against time

Now, you might ask — “What’s the whole point of EAFP? If I can avoid exceptions by first verifying the existance of a key, I am good. Why are you trying to sell me a new religion?”

Put down your pitchforks!

The advantage of EAFP over LBYL is that it avoids the classic race condition bug. How so? Well, let’s suppose that in the LYBL approach, between the time we check for the key and modify its value, some other program deletes the key from the dictionary. Guess what? You got played. Even though the key existed just a few microseconds ago, it was erased and now you’ll encounter a KeyError exception.

EAFP bypasses this bug altogether by not engaging in all the unnecessary gymnastics.

References:

Previously published at https://medium.com/@jaintj95/easier-to-ask-for-forgiveness-than-permission-a-tale-of-pythons-eccentricity-1992bb6b0764

read original article here