Skip to main content
ClaudeWave
Skill85 repo starsupdated 3mo ago

dead-code-eliminator

Identify and analyze unused or redundant code including unused functions/methods, unused variables/imports, unreachable code, and redundant conditions. Use when cleaning up codebases, improving maintainability, reducing technical debt, or conducting code quality audits. Analyzes Python code using AST analysis and produces markdown reports listing dead code locations with line numbers, severity ratings, and recommendations. Triggers when users ask to find dead code, remove unused code, identify unused imports, find unreachable code, or clean up redundant logic.

Install in Claude Code
Copy
git clone --depth 1 https://github.com/ArabelaTso/Skills-4-SE /tmp/dead-code-eliminator && cp -r /tmp/dead-code-eliminator/skills/dead-code-eliminator ~/.claude/skills/dead-code-eliminator
Then start a new Claude Code session; the skill loads automatically.

SKILL.md

# Dead Code Eliminator

## Overview

Systematically identify unused or redundant code in Python codebases to improve maintainability, reduce confusion, and eliminate technical debt.

## Workflow

### 1. Understand the Scope

Define what to analyze:

**Questions to ask:**
- What directory or files should be analyzed?
- Should test files be included or excluded?
- Are there specific types of dead code to focus on?
- Should external-facing API functions be considered?

**Determine analysis scope:**
```bash
# Check project structure
ls -la

# Count Python files
find . -name "*.py" | wc -l

# Identify test directories
find . -type d -name "*test*"
```

### 2. Identify Dead Code

Use multiple detection strategies to find different types of dead code.

#### Strategy 1: Find Unused Functions

Use the bundled script for AST-based analysis:

```bash
# Scan entire project
python scripts/find_unused_functions.py /path/to/project

# Exclude specific directories
python scripts/find_unused_functions.py /path/to/project tests,venv,docs
```

**What it detects:**
- Functions defined but never called
- Methods that aren't invoked anywhere
- Async functions without callers

**Limitations:**
- Won't detect dynamically called functions (via getattr, decorators)
- May flag public API functions that are used externally
- Doesn't detect pytest fixtures or entry points

#### Strategy 2: Find Unused Imports

Use the bundled script to identify unused imports:

```bash
# Scan single file
python scripts/find_unused_imports.py /path/to/file.py

# Scan entire directory
python scripts/find_unused_imports.py /path/to/project

# Exclude directories
python scripts/find_unused_imports.py /path/to/project venv,.venv,tests
```

**What it detects:**
- Imports that are never referenced
- Unused `from X import Y` statements
- Redundant imports

#### Strategy 3: Use External Tools

Leverage Python ecosystem tools for comprehensive analysis:

**vulture** - Finds unused code:
```bash
# Install
pip install vulture

# Run on project
vulture /path/to/project

# Exclude directories
vulture /path/to/project --exclude venv,tests

# Set minimum confidence (0-100)
vulture /path/to/project --min-confidence 80
```

**autoflake** - Focuses on imports and variables:
```bash
# Install
pip install autoflake

# Check for unused imports
autoflake --check --imports /path/to/file.py

# Check unused imports and variables
autoflake --check --remove-all-unused-imports --remove-unused-variables /path/to/file.py

# Recursive scan
autoflake --check -r /path/to/project
```

**pylint** - General linting including dead code:
```bash
# Install
pip install pylint

# Check for unused variables, imports, functions
pylint /path/to/project --disable=all --enable=unused-import,unused-variable,unreachable
```

#### Strategy 4: Manual Code Review

Read the code to identify patterns:

**Unreachable code:**
- Code after `return` statements
- Code in impossible conditions
- Code after `break`, `continue`, or `raise`

**Redundant conditions:**
- Always-true or always-false checks
- Duplicate conditions
- Unnecessary `else` after `return`

**Look for:**
```bash
# Find code after return statements (basic pattern)
grep -A 3 "return" **/*.py | grep -v "^--$"

# Find functions with "old" or "legacy" in name
grep -r "def.*old\|def.*legacy" .

# Find TODO comments about removal
grep -r "TODO.*remove\|FIXME.*delete" .
```

### 3. Categorize Findings

Organize dead code by type and priority.

See [dead-code-patterns.md](references/dead-code-patterns.md) for comprehensive pattern catalog.

#### Category: Unused Imports

**Priority:** High (easy to remove, low risk)

**Examples:**
- `import os` but os is never used
- `from typing import List, Dict` but only `List` is used
- Duplicate imports

#### Category: Unused Functions/Methods

**Priority:** Medium to High

**Subcategories:**
- **Orphaned helpers:** Utility functions never called
- **Refactoring leftovers:** Old implementations not removed
- **Test helpers:** Test utilities not used by any test

**Caution - May be intentional:**
- Public API functions (used externally)
- Plugin/hook functions (called dynamically)
- CLI entry points (called from command line)

#### Category: Unreachable Code

**Priority:** High (indicates bugs or confusion)

**Examples:**
- Code after `return`
- Code in impossible conditions
- Code after `raise`

#### Category: Redundant Code

**Priority:** Medium

**Examples:**
- Redundant boolean checks
- Unnecessary `else` after `return`
- Duplicate logic in multiple places

#### Category: Unused Variables

**Priority:** Low to Medium

**Examples:**
- Assigned but never read
- Function parameters never used
- Loop variables never referenced

### 4. Verify Findings

Before reporting, verify that identified code is truly dead.

**Check for dynamic usage:**
```python
# Code may appear unused but is called dynamically
handlers = {
    'process': process_handler,  # Looks unused but isn't
}

# Or via getattr
handler = getattr(module, function_name)
```

**Check for external usage:**
- Is this a public API function?
- Is it documented in README or API docs?
- Is it an entry point in setup.py?

**Check for framework conventions:**
```python
# Django signal handlers
@receiver(post_save, sender=User)
def user_saved(sender, instance, **kwargs):  # May appear unused
    pass

# Pytest fixtures
@pytest.fixture
def sample_data():  # Used by tests but not "called" directly
    return {"key": "value"}
```

**Verify with grep:**
```bash
# Search for function name in entire codebase
grep -r "function_name" .

# Search in quotes (dynamic calls)
grep -r "'function_name'\|\"function_name\"" .

# Search in setup.py or config files
grep -r "function_name" setup.py pyproject.toml
```

### 5. Generate Report

Create a structured markdown report of findings.

## Dead Code Analysis Report

**Project:** [Project Name]
**Analyzed:** [Date]
**Scope:** [Directories analyzed]
**Excluded:** [Excluded directories]

---

## Summary

- **Unu
abstract-domain-explorerSkill

Applies abstract interpretation using different abstract domains (intervals, octagons, polyhedra, sign, congruence) to statically analyze program variables and infer invariants, value ranges, and relationships. Use when analyzing program properties, inferring loop invariants, detecting potential errors, or understanding variable relationships through static analysis.

abstract-invariant-generatorSkill

Uses abstract interpretation to automatically infer loop invariants, function preconditions, and postconditions for formal verification. Generates invariants that capture program behavior and support correctness proofs in Dafny, Isabelle, Coq, and other verification systems. Use when adding formal specifications to code, generating verification conditions, inferring contracts for functions, or discovering loop invariants for proofs.

abstract-state-analyzerSkill

Performs abstract interpretation over source code to infer possible program states, variable ranges, and data properties without executing the program. Reports potential runtime errors including out-of-bounds accesses, null dereferences, type inconsistencies, division by zero, and integer overflows. Use when analyzing code for potential runtime errors, performing static analysis, checking safety properties, or verifying program behavior without execution.

abstract-trace-summarizerSkill

Performs abstract interpretation to produce summarized execution traces and high-level program behavior representations. Highlights key control flow paths, variable relationships, loop invariants, function summaries, and potential runtime states using abstract domains (intervals, signs, nullness, etc.). Use when analyzing program behavior, understanding execution paths, computing loop invariants, tracking variable ranges, detecting potential runtime errors, or generating program summaries without concrete execution.

acsl-annotation-assistantSkill

Create ACSL (ANSI/ISO C Specification Language) formal annotations for C/C++ programs. Use this skill when working with formal verification, adding function contracts (requires/ensures), loop invariants, assertions, memory safety annotations, or any ACSL specifications. Supports Frama-C verification and generates comprehensive formal specifications for C/C++ code.

agent-browserSkill

CLI-based browser automation with persistent page state using ref-based element interaction. Use when users ask to navigate websites, interact with web pages, fill forms, take screenshots, test web applications, or extract information from web pages.

ambiguity-detectorSkill

Detects and analyzes ambiguous language in software requirements and user stories. Use when reviewing requirements documents, user stories, specifications, or any software requirement text to identify vague quantifiers, unclear scope, undefined terms, missing edge cases, subjective language, and incomplete specifications. Provides detailed analysis with clarifying questions and suggested improvements.

api-design-assistantSkill

Design and review APIs with suggestions for endpoints, parameters, return types, and best practices. Use when designing new APIs from requirements, reviewing existing API designs, generating API documentation, or getting implementation guidance. Supports REST APIs with focus on endpoint structure, request/response schemas, authentication, pagination, filtering, versioning, and OpenAPI specifications. Triggers when users ask to design, review, document, or improve APIs.