Explaning ‘Look before you Leap’ VS ‘Easier to Ask Forgivness than Permission’ styles in Python
The aim of this explainer💡 is to oppose “Easier to Ask Forgiveness than Permission” style in Python VS “Look before you Leap” style typical for C (allegedly:) in the use case of file deletion. I know it is typical for coding style, but you may apply this to other cases — my particular case is deploying EKS clusters which are sometimes problematic due to access (IAM) issues. Should I check first (LBYL) or go ahead and handle issues only when they arise (EAFP). Examples are simpler ones, just deleting a file.
2 min readOct 23, 2023
1. EAFP
- Easier to ask for forgiveness than permission.
- This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false.
- This clean and fast style is characterized by the presence of many try and except statements.
- The technique contrasts with the LBYL style common to many other languages such as
import os
def delete_file_eafp(filepath):
"""Deletes the file at the given filepath, if it exists.
Args:
filepath: The filepath of the file to delete.
"""
try:
os.remove(filepath)
except Exception as e:
# Handle the error here, e.g. log it or notify the user.
pass
2. LBYL
- Look before you leap.
- Test-Path style
- This coding style explicitly tests for pre-conditions before making calls or lookups.
- This style contrasts with the EAFP approach and is characterized by the presence of many if statements.
- In a multi-threaded environment, the LBYL approach can risk introducing a race condition between “the looking” and “the leaping”.
- For example, the code,
if key in mapping: return mapping[key]
can fail if another thread removes key from mapping after the test, but before the lookup. - This issue can be solved with locks or by using the EAFP approach.
import os
def delete_file_lbyl(filepath):
"""Deletes the file at the given filepath, if it exists.
Args:
filepath: The filepath of the file to delete.
"""
if os.path.exists(filepath):
os.remove(filepath)