Dead code refers to code that is not being used or referenced anywhere in your codebase.However, it’s important to note that some code might appear unused but should not be deleted, including:
Test files and test functions
Functions with decorators (which may be called indirectly)
Public API endpoints
Event handlers or callback functions
Code used through reflection or dynamic imports
This guide will show you how to safely identify and remove genuinely unused code while preserving important functionality.
# Iterate through all functions in the codebasefor function in codebase.functions: # Remove functions with no usages if not function.usages: function.remove()# Commitcodebase.commit()
This will remove all code that is not explicitly referenced elsewhere, including tests, endpoints, etc. This is almost certainly not what you want. We recommend further filtering.
To filter out special cases that are not explicitly referenced yet are, nonetheless, worth keeping around, you can use the following pattern:
Copy
Ask AI
for function in codebase.functions: # Skip test files if "test" in function.file.filepath: continue # Skip decorated functions if function.decorators: continue # Skip public routes, e.g. next.js endpoints # (Typescript only) if 'routes' in function.file.filepath and function.is_jsx: continue # ... etc. # Check if the function has no usages and no call sites if not function.usages and not function.call_sites: # Print a message indicating the removal of the function print(f"Removing unused function: {function.name}") # Remove the function from the file function.remove()# Commitcodebase.commit()
To remove unused variables, you can check for their usages within their scope:
typescript
Copy
Ask AI
for func in codebase.functions: # Iterate through local variable assignments in the function for var_assignments in func.code_block.local_var_assignments: # Check if the local variable assignment has no usages if not var_assignments.local_usages: # Remove the local variable assignment var_assignments.remove()# Commitcodebase.commit()
After removing dead code, you may need to clean up any remaining artifacts:
Copy
Ask AI
for file in codebase.files: # Check if the file is empty if not file.content.strip(): # Print a message indicating the removal of the empty file print(f"Removing empty file: {file.filepath}") # Remove the empty file file.remove()# commit is NECESSARY to remove the files from the codebasecodebase.commit()# Remove redundant newlinesfor file in codebase.files: # Replace three or more consecutive newlines with two newlines file.edit(re.sub(r"\n{3,}", "\n\n", file.content))