Codegen’s GraphSitter library provides powerful APIs for identifying and removing dead code from your codebase. This guide will walk you through the process of detecting and deleting unused functions, classes, and imports.

Common use cases include:

  • Removing unused functions and methods
  • Eliminating dead imports
  • Cleaning up unused variables and parameters

Overview

Deleting dead code involves identifying unused elements and safely removing them. Here’s a basic example:

Removing Unused Functions

To remove unused functions, you can check for the absence of usages and call sites:

Eliminating Dead Imports

To remove unused imports, you can check if the imported symbol has any usages:

Cleaning Up Unused Variables

To remove unused variables, you can check for their usages within their scope:

Ignoring False Positives

Every codebase is different, and usually there’s a (small) set of things that could look like dead code but aren’t.

Simply tell the assistant to avoid certain cases (like files starting with test_, or children of a specific class).

Removing Dead Classes

To remove unused classes, check for the absence of usages:

Cleaning Up After Removal

After removing dead code, you may need to clean up any remaining artifacts:

Best Practices

  1. Use Caution: Always double-check before removing code, especially for elements that might be used dynamically or in hard-to-detect ways.

  2. Incremental Removal: Remove dead code in stages, committing and testing after each stage to ensure you haven’t broken anything.

  3. Consider Visibility: Be extra cautious when removing public APIs or elements that might be used by external code.

  4. Update Documentation: After removing dead code, update any related documentation or comments to maintain consistency.

  5. Use Version Control: Always perform these operations in a version-controlled environment, so you can easily revert changes if needed.

By following these guidelines, you can effectively clean up your codebase by removing dead code while maintaining its integrity and functionality.