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.
Overview
To simply identify code without any external usages, you can check for the absence of Symbol.usages.
# Iterate through all functions in the codebase
for function in codebase.functions:
# Remove functions with no usages
if not function.usages:
function.remove()
# Commit
codebase.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.
Filtering for Special Cases
To filter out special cases that are not explicitly referenced yet are, nonetheless, worth keeping around, you can use the following pattern:
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()
# Commit
codebase.commit()
Cleaning Up Unused Variables
To remove unused variables, you can check for their usages within their scope:
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()
# Commit
codebase.commit()
Cleaning Up After Removal
After removing dead code, you may need to clean up any remaining artifacts:
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 codebase
codebase.commit()
# Remove redundant newlines
for file in codebase.files:
# Replace three or more consecutive newlines with two newlines
file.edit(re.sub(r"\n{3,}", "\n\n", file.content))