Best practices and guidelines for Python code refactoring.
This skill provides guidance for refactoring Python code to improve readability, maintainability, and performance while preserving functionality.
Break down large functions into smaller, focused units:
user_count not n)calculate_total not calc)OrderProcessor not OP)# Before
def process(d):
if d['type'] == 'a':
# 50 lines...
elif d['type'] == 'b':
# 50 lines...
# After
def process(data: ProcessData) -> Result:
handlers = {
'a': process_type_a,
'b': process_type_b,
}
handler = handlers.get(data.type, process_default)
return handler(data)
# Before
def get_user(id):
return db.find(id)
# After
def get_user(user_id: int) -> Optional[User]:
return db.find(user_id)
Move code blocks into separate functions.
Group related parameters into a class or dataclass.
Use inheritance or strategy pattern instead of if/else chains.
Use early returns and positive conditions.