Module 15: Best PracticesWriting code others (and you) won't hate
Clean code is code that's easy to read, easy to change, and easy to reason about. It's one of the most valuable professional skills you can develop. Here's the core principle:
π The Rule of Clean CodeAlways code as if the person who ends up maintaining your code is a violent psychopath who knows where you live. Write code for humans first, computers second.
Naming Conventions
Names should tell a story. A reader should be able to understand what a variable holds or what a function does from its name alone β no comments required:
# Bad naming
x = 86400
def calc(a, b):
return a * b * 0.075
# Good naming
SECONDS_IN_A_DAY = 86400
def calculate_tax(price, tax_rate):
return price * tax_rate
# Python naming conventions:
variable_name = 'use snake_case'
CONSTANT_VALUE = 'use ALL_CAPS'
def function_name(): # snake_case
pass
class ClassName: # PascalCase
pass
The DRY Principle
DRY stands for Don't Repeat Yourself. If you find yourself writing the same code more than once, that code belongs in a function. Duplicated code is a maintenance nightmare β update it in one place and forget the other, and you have a bug.
# WET (Write Everything Twice) β BAD
print('--- User Report ---')
print(f'Name: Ama')
print(f'Score: 95')
print('-------------------')
print('--- User Report ---')
print(f'Name: Kofi')
print(f'Score: 78')
print('-------------------')
# DRY β GOOD
def print_user_report(name, score):
print('--- User Report ---')
print(f'Name: {name}')
print(f'Score: {score}')
print('-------------------')
print_user_report('Ama', 95)
print_user_report('Kofi', 78)
Code Readability
Beyond naming, readability comes from structure, spacing, and comments that add value (not noise):
# Bad β dense and cryptic
def p(u,s,i):return[x for x in s if x['uid']==u and x['score']>=i]
# Good β readable and maintainable
def get_passing_submissions(user_id, submissions, min_score):
"""
Returns all submissions by a user that meet the minimum score.
Args:
user_id: The ID of the user
submissions: List of submission dictionaries
min_score: Minimum score threshold (inclusive)
"""
passing = []
for submission in submissions:
belongs_to_user = submission['uid'] == user_id
meets_threshold = submission['score'] >= min_score
if belongs_to_user and meets_threshold:
passing.append(submission)
return passing
Basic Optimization Techniques
Don't optimize prematurely β but know these patterns for when it matters:
- Use list comprehensions instead of loops for simple transformations (faster and more Pythonic).
- Use dictionaries for lookups instead of searching through lists (O(1) vs O(n)).
- Use generators for large datasets to save memory (process one item at a time).
- Profile before optimizing β measure which parts are actually slow before rewriting them.
# List comprehension vs loop
squares_loop = []
for x in range(10):
squares_loop.append(x ** 2)
squares_comp = [x ** 2 for x in range(10)] # Cleaner, faster
# Dictionary lookup vs linear search
users_list = [{'id': 1, 'name': 'Ama'}, {'id': 2, 'name': 'Kofi'}]
# O(n) search:
found = next((u for u in users_list if u['id'] == 2), None)
users_dict = {1: 'Ama', 2: 'Kofi'}
# O(1) lookup:
found = users_dict.get(2) # Much faster for large datasets