(Collection of examples of anti-patterns in Python)
Understanding and avoiding anti-patterns is crucial for writing clean, maintainable, and efficient Python code.
with
to open fileswith
ensures proper file closing even if exceptions occur, preventing resource leaks or data corruption.with
requires manual closing, prone to error.def get_user_info(user_id):
if user_id in active_users:
return active_users[user_id] # Returns a dictionary
else:
return None # Returns NoneType
# This function might return a dictionary or None, making it less predictable and harder to use.
def get_user_info(user_id):
user = active_users.get(user_id) # Use .get() for consistent return type
return user or {} # Return an empty dictionary if user not found
get()
for default values in dictionariesdict.get(key, default)
provides a clean, one-line solution.items()
to iterate over dictionariesitems()
method.for key, value in my_dict.items():
simplifies iteration and avoids indexing errors.def my_function():
critial_data = get_critical_data()
process_data(critial_data)
print(critial_data) # Debugger statement
# --- vs ---
import logging
def my_function():
critial_data = get_critical_data()
process_data(critial_data)
clean_data = process_data(critial_data)
location = save_artifact(clean_data)
logging.info(f"Processed data: {clean_data.id} @ {location}") # Logging statement
“It might seem impressive at first, but like a house of cards, one small change can bring the whole thing tumbling down. Refactoring becomes a religious experience.”
# Use with clear constants:
def calculate_discount(price, discount_threshold=10):
if price > discount_threshold: # Hardcoded magic number
return price * 0.8 # Another magic number
else:
return price
# --- vs ---
DISCOUNT_THRESHOLD = 10 # Defined constant
DISCOUNT_RATE = 0.8 # Defined constant
def calculate_discount(price):
if price > DISCOUNT_THRESHOLD:
return price * DISCOUNT_RATE
else:
return price
✨ Bonus for reading all of this! ✨
Read more: Cargo cult programming