Dead Code Finder
The `deadcode` library is a static analysis tool for Python that identifies unused functions, classes, and variables within a codebase. It helps developers clean up projects by pinpointing code that is no longer reachable or imported. As of version 2.4.1, it focuses on providing a robust CLI experience with programmatic API access. The project maintains an active development cycle, with major releases incorporating significant refactors and minor releases for bug fixes and feature enhancements.
Common errors
-
deadcode: command not found
cause The `deadcode` executable is not in your system's PATH, or the package was not installed correctly.fixEnsure `pip install deadcode` completed without errors. If installed in a virtual environment, activate it. If using `pipx`, ensure `pipx ensurepath` has been run. -
Error: Invalid value for '--path': Path '/non_existent_path' does not exist.
cause The path provided to the `--path` argument does not exist or is inaccessible.fixVerify the path is correct and exists. Use an absolute path or ensure the relative path is correct from your current working directory. For example: `deadcode --path .` to scan the current directory. -
Error reading configuration file: No such file or directory: 'deadcode.toml'
cause The `deadcode` command expects a `deadcode.toml` configuration file in the working directory or specified path if you're trying to use custom configuration.fixIf you don't need custom configuration, remove any `--config` flag or ensure the `deadcode.toml` file exists in the expected location. To generate a default config, you might need to run `deadcode config init` if such a command exists (check documentation).
Warnings
- breaking Version 2.0.0 introduced significant breaking changes, including a major refactor of the internal parsing logic, CLI arguments, and configuration. If upgrading from pre-2.0.0 versions, direct code and config might break.
- breaking The `exclude_dirs` argument was removed from both the CLI and programmatic `find_dead_code` function in version 2.0.0. Its functionality has been merged into `exclude_patterns`.
- gotcha Static analysis tools like `deadcode` may produce false positives or negatives, especially with highly dynamic code, complex import mechanisms (e.g., `__import__`, `importlib`), or when code is generated at runtime.
Install
-
pip install deadcode
Imports
- find_dead_code
from deadcode.finder import find_dead_code
- default_config
from deadcode.config import default_config
Quickstart
import subprocess
import json
import tempfile
from pathlib import Path
import shutil
# Create a temporary directory to simulate a project
temp_dir = Path(tempfile.mkdtemp())
# Create dummy Python files within the temporary project
# my_module.py contains an unused function
(temp_dir / "my_module.py").write_text("""
def used_func():
return "hello"
def unused_func():
return "world"
""")
# main.py imports and uses 'used_func', leaving 'unused_func' dead
(temp_dir / "main.py").write_text("""
from my_module import used_func
print(used_func())
""")
# Define the output report file path
output_file = temp_dir / "deadcode_report.json"
try:
print(f"Scanning directory: {temp_dir}")
# Run the deadcode CLI tool
result = subprocess.run(
["deadcode", "--path", str(temp_dir), "--output", str(output_file)],
capture_output=True,
text=True,
check=True # Will raise CalledProcessError if command fails
)
print("\n--- CLI STDOUT ---")
print(result.stdout)
if result.stderr:
print("\n--- CLI STDERR ---")
print(result.stderr)
# Check if the report file was generated and print its content
if output_file.exists():
with open(output_file, 'r') as f:
report = json.load(f)
print("\n--- DEAD CODE REPORT ---")
print(json.dumps(report, indent=2))
else:
print("\nNo dead code report file generated.")
except subprocess.CalledProcessError as e:
print(f"\nERROR: deadcode command failed with exit code {e.returncode}")
print(f"Stdout: {e.stdout}")
print(f"Stderr: {e.stderr}")
except FileNotFoundError:
print("\nERROR: 'deadcode' command not found. Please ensure the 'deadcode' package is installed and its executable is in your system's PATH.")
finally:
# Clean up the temporary directory and its contents
if temp_dir.exists():
print(f"\nCleaning up temporary directory: {temp_dir}")
shutil.rmtree(temp_dir)