Skip to main content
hooksSource-backedReview first Safety Privacy

Python Import Optimizer - Hooks

Automatically sorts and optimizes Python imports using isort when Python files are modified.

by JSONbored·added 2025-09-19·
HarnessClaude Code
Trigger:PostToolUse
Review first review before installing

Open the source and read safety notes before installing.

Citation facts

Source-backed facts for citing this resource, derived directly from the registry — also available as plain text for AI assistants.

Source URLs
https://pycqa.github.io/isort/, https://github.com/JSONbored/awesome-claude/blob/main/content/hooks/python-import-optimizer.mdx
Safety notes
Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.
Privacy notes
Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.
Author
JSONbored
Claim status
unclaimed
Last verified
2025-09-19

Decision playbook

Review trust signals before you adopt

Signals are present but mixed. Use the checklist below to confirm the source and operational safety for your environment.

Compare context
Selected

0

Current score

78

Baseline

Delta

No baseline selected

No major trust-signal divergence detected in the current selection.

Source and provenance checks

Complete

Confirm ownership and provenance before trusting install instructions.

  • Source link availableRequired

    Open the canonical repository and verify ownership.

    Done
  • Source provenance statusRequired

    Marked as source-backed.

    Done
  • Metadata reviewed

    Registry metadata indicates a reviewed listing.

    Done

Safety and privacy checks

Complete

Validate risk disclosures before installation or API wiring.

  • Safety notes presentRequired

    Review the listed safety guidance before running commands.

    Done
  • Privacy notes presentRequired

    Review data handling notes before connecting accounts or secrets.

    Done
  • Trust level risk gateRequired

    Trust level does not block evaluation.

    Done

Package and install checks

Needs review

Check package metadata and artifact integrity signals.

  • Install payload available

    Install or copy payload is available for review.

    Done
  • Package verification flag

    No package verification flag provided.

    Pending
  • Checksum metadata

    No checksum provided for downloaded artifact.

    Pending

Compare-driven decision checks

Needs review

Use compare context to validate trade-offs before adoption.

  • Compare tray has multiple entries

    Add at least one more entry to compare trust differences.

    Pending
  • Baseline comparison available

    No baseline peer selected yet.

    Pending
  • Diverging trust signals identified

    No major trust-signal divergence found.

    Pending

Setup at a glance

CLI install

Copy-ready — paste the snippet to get started.

Install command

Provided

Config snippet

Provided

Copy snippet

Provided

Prerequisites

None

Platforms

1 listed

Difficulty

0/100

Adoption plan

Balanced adoption plan

Current risk score 16/100. Use staged verification before broader rollout.

Risk 16

Pre-adoption checks

Validate source and review signals before any execution.

  • Confirm source provenanceRequired

    Source URL/provenance metadata is present.

    Done
  • Confirm metadata review state

    Listing has review metadata.

    Done
  • Verify install payload

    Install/config payload exists and can be inspected.

    Done

Security checks

Confirm safety, privacy, and package integrity signals.

  • Review safety notesRequired

    Safety notes are present.

    Done
  • Review privacy notesRequired

    Privacy notes are present.

    Done
  • Verify package integrity metadata

    No package verification/checksum metadata.

    Pending

Rollout

Adopt in controlled steps based on the selected plan.

  • Run in isolated sandbox firstRequired

    Use a constrained sandbox and observe behavior across multiple tasks.

    Pending
  • Roll out graduallyRequired

    Roll out to a small cohort before wider usage.

    Pending
  • Set monitoring and fallback

    Define rollback path and monitor errors after adoption.

    Pending

Evidence readiness

Evidence readiness matrix · balanced

Required evidence gates are covered (5/6 signals complete).

Risk 15

Source provenance

Present

Source repository/provenance is listed.

Required in this preset

Metadata review

Present

Review metadata is present.

Required in this preset

Safety notes

Present

Safety notes are present.

Required in this preset

Privacy notes

Present

Privacy notes are present.

Optional in this preset

Package integrity

Missing

Package integrity metadata is missing.

Optional in this preset

Install payload

Present

Install payload is available.

Required in this preset

Required evidence gates are covered for this preset.

Decision timeline

Decision timeline · balanced

5/6 steps complete with no blocking gaps for this preset.

Risk 14

triage

Confirm source provenanceRequired

Source/provenance metadata is available.

Done

triage

Check metadata review statusRequired

Review metadata is available.

Done

verify

Review safety notesRequired

Safety notes are available.

Done

verify

Review privacy notes

Privacy notes are available.

Done

verify

Validate package integrity metadata

Package integrity metadata is missing.

Pending

rollout

Verify install payload and commandsRequired

Install payload is available.

Done

No required blockers for this timeline preset.

Safety & privacy surface

Safety & privacy surface

1 safety and 1 privacy notes across 2 risk areas. Review closely: credentials & tokens, permissions & scopes.

2 areas
  • SafetyPermissions & scopesRuns automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.
  • PrivacyCredentials & tokensReceives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.

Safety notes

  • Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.

Privacy notes

  • Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.

Schema details

Install type
cli
Reading time
3 min
Difficulty score
0
Troubleshooting
Yes
Breaking changes
No
Skill and platform metadata
Retrieval sources
https://pycqa.github.io/isort/https://code.claude.com/docs/en/hooks
Runtime and command metadata
Trigger
PostToolUse
Script language
bash
Script body
#!/bin/bash

# Read the tool input from stdin
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name')
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')

if [ -z "$FILE_PATH" ]; then
  exit 0
fi

# Check if this is a Python file
if [[ "$FILE_PATH" == *.py ]]; then
    echo "🐍 Python Import Optimizer - Processing Python file..."
    echo "📄 File: $FILE_PATH"
    
    # Check if file exists
    if [ ! -f "$FILE_PATH" ]; then
        echo "⚠️ File not found: $FILE_PATH"
        exit 1
    fi
    
    # Step 1: Sort imports with isort
    echo "📋 Sorting imports with isort..."
    if command -v isort >/dev/null 2>&1; then
        if isort "$FILE_PATH" --profile black --line-length 88 --check-only --diff; then
            echo "✅ Imports are already sorted"
        else
            echo "🔄 Sorting imports..."
            isort "$FILE_PATH" --profile black --line-length 88
            echo "✅ Imports sorted successfully"
        fi
    else
        echo "⚠️ isort not found. Install with: pip install isort"
    fi
    
    # Step 2: Remove unused imports with autoflake (optional)
    echo "🧹 Removing unused imports..."
    if command -v autoflake >/dev/null 2>&1; then
        # Check for unused imports first
        if autoflake --check "$FILE_PATH" --remove-unused-variables --remove-all-unused-imports; then
            echo "✅ No unused imports found"
        else
            echo "🔄 Removing unused imports..."
            autoflake --in-place "$FILE_PATH" --remove-unused-variables --remove-all-unused-imports
            echo "✅ Unused imports removed"
        fi
    else
        echo "ℹ️ autoflake not found (optional). Install with: pip install autoflake"
    fi
    
    # Step 3: Additional import analysis
    echo "🔍 Analyzing import structure..."
    
    # Count different types of imports
    STDLIB_IMPORTS=$(grep -c "^import \(os\|sys\|re\|json\|datetime\|collections\|itertools\|functools\|pathlib\)" "$FILE_PATH" 2>/dev/null || echo 0)
    THIRD_PARTY_IMPORTS=$(grep -c "^\(import\|from\) \(numpy\|pandas\|requests\|flask\|django\|fastapi\)" "$FILE_PATH" 2>/dev/null || echo 0)
    RELATIVE_IMPORTS=$(grep -c "^from \.[.]*" "$FILE_PATH" 2>/dev/null || echo 0)
    
    echo "📊 Import Summary:"
    echo "  • Standard Library: $STDLIB_IMPORTS"
    echo "  • Third Party: $THIRD_PARTY_IMPORTS"
    echo "  • Relative: $RELATIVE_IMPORTS"
    
    # Check for potential issues
    if grep -q "^import \*" "$FILE_PATH" 2>/dev/null; then
        echo "⚠️ Warning: Star imports detected (import *) - consider specific imports"
    fi
    
    if [ "$(grep -c '^import\|^from' "$FILE_PATH" 2>/dev/null || echo 0)" -gt 20 ]; then
        echo "💡 Tip: Consider grouping related imports or using a package structure"
    fi
    
    echo ""
    echo "💡 Python Import Tips:"
    echo "  • Use absolute imports when possible"
    echo "  • Group imports: stdlib, third-party, local"
    echo "  • Avoid star imports (import *)"
    echo "  • Use 'from module import specific_function' for clarity"
    
    echo ""
    echo "🎯 Python import optimization complete!"
    
else
    echo "ℹ️ File is not a Python file: $FILE_PATH"
fi

exit 0
Full copyable content
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/python-import-optimizer.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}

About this resource

Features

  • Automatic import sorting with isort including isort integration (isort command execution with PEP 8 compliant sorting, import grouping by type with standard library/third-party/local separation, import alphabetization with consistent ordering, import formatting with consistent style), PEP 8 compliant import organization (PEP 8 import ordering standards with standard library first, third-party imports second, local imports last, import grouping with blank line separation, import sorting with alphabetical ordering), import configuration (pyproject.toml configuration for isort settings, setup.cfg configuration for isort settings, .isort.cfg configuration for isort settings, configuration file support for project-wide settings), and import validation (import syntax validation with syntax checking, import order validation with order checking, import format validation with format checking)
  • PEP 8 compliant import organization including PEP 8 standards (PEP 8 import ordering standards with standard library first, third-party imports second, local imports last, import grouping with blank line separation, import sorting with alphabetical ordering), import grouping (standard library imports grouped together, third-party imports grouped together, local imports grouped together, blank line separation between groups), import sorting (alphabetical sorting within each group, consistent import ordering across project, import ordering standards compliance), and import formatting (consistent import formatting with PEP 8 style, import line formatting with proper spacing, import statement formatting with consistent style)
  • Unused import removal including autoflake integration (autoflake command execution with unused import detection, unused variable removal with --remove-unused-variables flag, unused import removal with --remove-all-unused-imports flag, import analysis with AST parsing), import cleanup (unused import detection with static analysis, unused import removal with safe removal, import optimization with code cleanup), import validation (import usage analysis with dependency tracking, import safety checks with usage validation, import optimization suggestions with recommendations), and import safety (safe import removal with usage validation, import preservation with # noqa comments, import exclusion with configuration options)
  • Black profile compatibility including Black integration (isort --profile black flag for Black compatibility, line length configuration with --line-length 88 for Black default, import formatting with Black-compatible style, import ordering with Black-compatible ordering), Black profile settings (profile black configuration for consistent formatting, line length 88 matching Black default, import style matching Black preferences, import formatting matching Black output), Black compatibility (Black-compatible import sorting with consistent style, Black-compatible import formatting with matching output, Black-compatible import ordering with consistent ordering), and Black workflow integration (automatic import sorting before Black formatting, import formatting compatible with Black output, import ordering compatible with Black preferences)
  • Import grouping by type including standard library imports (standard library import detection with built-in module detection, standard library import grouping with stdlib section, standard library import sorting with alphabetical ordering), third-party imports (third-party import detection with external package detection, third-party import grouping with third-party section, third-party import sorting with alphabetical ordering), local imports (local import detection with project module detection, local import grouping with local section, local import sorting with alphabetical ordering), and import section separation (blank line separation between import groups, import section organization with clear separation, import section formatting with consistent style)
  • Code formatting integration including formatting integration (isort integration with code formatters like Black, Ruff, autopep8, formatting compatibility with multiple formatters, formatting consistency with project standards), formatting configuration (pyproject.toml configuration for isort settings, setup.cfg configuration for isort settings, .isort.cfg configuration for isort settings, configuration file support for project-wide settings), formatting workflow (automatic formatting on file changes, formatting consistency across project, formatting integration with development workflow), and formatting tools (Black integration with isort, Ruff integration with isort, autopep8 integration with isort, multiple formatter support)
  • Import analysis and statistics including import analysis (import count by type with standard library/third-party/local counts, import structure analysis with import hierarchy, import dependency analysis with dependency tracking), import statistics (import count statistics with detailed counts, import type statistics with type distribution, import usage statistics with usage tracking), import warnings (star import warnings with import * detection, large import count warnings with import count thresholds, import optimization suggestions with recommendations), and import reporting (import summary reporting with detailed summary, import analysis reporting with analysis results, import optimization reporting with optimization suggestions)
  • Development workflow integration including continuous optimization (real-time import optimization on file changes, immediate import sorting on file updates, automatic import cleanup on file modifications), workflow automation (automated import optimization without manual intervention, import sorting automation with automatic sorting, import cleanup automation with automatic cleanup), and workflow optimization (import change detection with change tracking, incremental import optimization with optimization, import consistency maintenance with consistency checks)

Use Cases

  • Organize Python imports according to PEP 8 standards automatically sorting imports with PEP 8 ordering, grouping imports by type with standard library/third-party/local separation, and maintaining consistent import formatting across projects
  • Remove unused imports automatically detecting unused imports with static analysis, removing unused imports safely with usage validation, and optimizing import statements for cleaner code
  • Group imports by type (standard library, third-party, local) automatically detecting import types, grouping imports by type with proper separation, and maintaining consistent import organization
  • Maintain consistent import formatting across projects automatically formatting imports with consistent style, ensuring import consistency across project files, and maintaining project-wide import standards
  • Integrate with Black code formatter automatically sorting imports with Black-compatible style, formatting imports with Black-compatible formatting, and ensuring seamless integration with Black workflow
  • Development workflow integration seamlessly integrating Python import optimization into development workflows without manual import sorting or cleanup

Installation

  1. Create hooks directory: mkdir -p .claude/hooks
  2. Create hook file: touch .claude/hooks/python-import-optimizer.sh
  3. Make executable: chmod +x .claude/hooks/python-import-optimizer.sh
  4. Add configuration from Hook Configuration section above to .claude/settings.json or ~/.claude/settings.json
  5. Alternative: Use the interactive /hooks command in Claude Code

Config paths

  • Local (not committed): .claude/settings.local.json
  • User settings (global): ~/.claude/settings.json
  • Project-wide (committed): .claude/settings.json

Requirements

  • Claude Code CLI installed
  • Project directory initialized
  • Bash shell available
  • Python 3.8+ installed
  • isort installed (pip install isort)
  • autoflake installed (optional, pip install autoflake)
  • jq (optional, for JSON parsing)

Hook Configuration

{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/python-import-optimizer.sh",
      "matchers": ["write", "edit"]
    }
  }
}

Hook Script

#!/bin/bash

# Read the tool input from stdin
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name')
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')

if [ -z "$FILE_PATH" ]; then
  exit 0
fi

# Check if this is a Python file
if [[ "$FILE_PATH" == *.py ]]; then
    echo "🐍 Python Import Optimizer - Processing Python file..."
    echo "📄 File: $FILE_PATH"

    # Check if file exists
    if [ ! -f "$FILE_PATH" ]; then
        echo "⚠️ File not found: $FILE_PATH"
        exit 1
    fi

    # Step 1: Sort imports with isort
    echo "📋 Sorting imports with isort..."
    if command -v isort >/dev/null 2>&1; then
        if isort "$FILE_PATH" --profile black --line-length 88 --check-only --diff; then
            echo "✅ Imports are already sorted"
        else
            echo "🔄 Sorting imports..."
            isort "$FILE_PATH" --profile black --line-length 88
            echo "✅ Imports sorted successfully"
        fi
    else
        echo "⚠️ isort not found. Install with: pip install isort"
    fi

    # Step 2: Remove unused imports with autoflake (optional)
    echo "🧹 Removing unused imports..."
    if command -v autoflake >/dev/null 2>&1; then
        # Check for unused imports first
        if autoflake --check "$FILE_PATH" --remove-unused-variables --remove-all-unused-imports; then
            echo "✅ No unused imports found"
        else
            echo "🔄 Removing unused imports..."
            autoflake --in-place "$FILE_PATH" --remove-unused-variables --remove-all-unused-imports
            echo "✅ Unused imports removed"
        fi
    else
        echo "ℹ️ autoflake not found (optional). Install with: pip install autoflake"
    fi

    # Step 3: Additional import analysis
    echo "🔍 Analyzing import structure..."

    # Count different types of imports
    STDLIB_IMPORTS=$(grep -c "^import \(os\|sys\|re\|json\|datetime\|collections\|itertools\|functools\|pathlib\)" "$FILE_PATH" 2>/dev/null || echo 0)
    THIRD_PARTY_IMPORTS=$(grep -c "^\(import\|from\) \(numpy\|pandas\|requests\|flask\|django\|fastapi\)" "$FILE_PATH" 2>/dev/null || echo 0)
    RELATIVE_IMPORTS=$(grep -c "^from \.[.]*" "$FILE_PATH" 2>/dev/null || echo 0)

    echo "📊 Import Summary:"
    echo "  • Standard Library: $STDLIB_IMPORTS"
    echo "  • Third Party: $THIRD_PARTY_IMPORTS"
    echo "  • Relative: $RELATIVE_IMPORTS"

    # Check for potential issues
    if grep -q "^import \*" "$FILE_PATH" 2>/dev/null; then
        echo "⚠️ Warning: Star imports detected (import *) - consider specific imports"
    fi

    if [ "$(grep -c '^import\|^from' "$FILE_PATH" 2>/dev/null || echo 0)" -gt 20 ]; then
        echo "💡 Tip: Consider grouping related imports or using a package structure"
    fi

    echo ""
    echo "💡 Python Import Tips:"
    echo "  • Use absolute imports when possible"
    echo "  • Group imports: stdlib, third-party, local"
    echo "  • Avoid star imports (import *)"
    echo "  • Use 'from module import specific_function' for clarity"

    echo ""
    echo "🎯 Python import optimization complete!"

else
    echo "ℹ️ File is not a Python file: $FILE_PATH"
fi

exit 0

Examples

Python Import Optimizer Hook Script

Complete hook script that performs Python import optimization

#!/bin/bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
if [ -z "$FILE_PATH" ]; then
  exit 0
fi
if [[ "$FILE_PATH" == *.py ]]; then
  echo "🐍 Python Import Optimizer - Processing Python file..."
  if command -v isort >/dev/null 2>&1; then
    echo "📋 Sorting imports with isort..."
    isort "$FILE_PATH" --profile black --line-length 88
    echo "✅ Imports sorted successfully"
  else
    echo "⚠️ isort not found. Install with: pip install isort"
  fi
fi
exit 0

Hook Configuration

Complete hook configuration for .claude/settings.json to enable Python import optimization

{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/python-import-optimizer.sh",
      "matchers": ["write", "edit"]
    }
  }
}

Import Sorting with Unused Import Removal

Enhanced hook script with isort sorting and autoflake unused import removal

#!/bin/bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
if [[ "$FILE_PATH" == *.py ]]; then
  if command -v isort >/dev/null 2>&1; then
    echo "📋 Sorting imports with isort..."
    if isort "$FILE_PATH" --profile black --line-length 88 --check-only --diff; then
      echo "✅ Imports are already sorted"
    else
      echo "🔄 Sorting imports..."
      isort "$FILE_PATH" --profile black --line-length 88
      echo "✅ Imports sorted successfully"
    fi
  fi
  if command -v autoflake >/dev/null 2>&1; then
    echo "🧹 Removing unused imports..."
    if autoflake --check "$FILE_PATH" --remove-unused-variables --remove-all-unused-imports; then
      echo "✅ No unused imports found"
    else
      echo "🔄 Removing unused imports..."
      autoflake --in-place "$FILE_PATH" --remove-unused-variables --remove-all-unused-imports
      echo "✅ Unused imports removed"
    fi
  fi
fi
exit 0

Import Analysis and Statistics

Enhanced hook script with import analysis and statistics reporting

#!/bin/bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
if [[ "$FILE_PATH" == *.py ]]; then
  if command -v isort >/dev/null 2>&1; then
    echo "📋 Sorting imports with isort..."
    isort "$FILE_PATH" --profile black --line-length 88
    echo "🔍 Analyzing import structure..."
    STDLIB_IMPORTS=$(grep -c "^import \(os\|sys\|re\|json\|datetime\|collections\|itertools\|functools\|pathlib\)" "$FILE_PATH" 2>/dev/null || echo 0)
    THIRD_PARTY_IMPORTS=$(grep -c "^\(import\|from\) \(numpy\|pandas\|requests\|flask\|django\|fastapi\)" "$FILE_PATH" 2>/dev/null || echo 0)
    RELATIVE_IMPORTS=$(grep -c "^from \\." "$FILE_PATH" 2>/dev/null || echo 0)
    echo "📊 Import Summary:"
    echo "  • Standard Library: $STDLIB_IMPORTS"
    echo "  • Third Party: $THIRD_PARTY_IMPORTS"
    echo "  • Relative: $RELATIVE_IMPORTS"
    if grep -q "^import \\*" "$FILE_PATH" 2>/dev/null; then
      echo "⚠️ Warning: Star imports detected (import *) - consider specific imports"
    fi
  fi
fi
exit 0

pyproject.toml Configuration

Example pyproject.toml configuration for isort and Black integration

[tool.isort]
profile = "black"
line_length = 88
known_first_party = ["myproject"]
skip_glob = ["*/migrations/*", "*/__pycache__/*"]

[tool.black]
line-length = 88
target-version = ["py312"]
include = '\.pyi?$'

Troubleshooting

isort conflicts with Black formatter settings

Hook already uses --profile black flag for compatibility. Ensure Black and isort versions are current. Add .isort.cfg with profile = black and line_length = 88 for project-wide consistency. Verify pyproject.toml configuration. Test with various Black versions.

autoflake removes imports that are actually used

Add # noqa comments to imports that should be preserved. Configure autoflake to exclude specific files with --exclude in hook script, or use all exports to signal intentional module-level imports. Verify import usage. Test with various autoflake configurations.

Hook processes init.py and breaks package exports

Exclude init.py from autoflake processing by modifying hook to check filename. Add special handling for package files where import * is intentional for re-exporting. Verify package structure. Test with various package configurations.

Relative imports get converted to absolute incorrectly

Configure isort with known_first_party setting in setup.cfg or pyproject.toml. Use --src-path flag in hook to help isort determine project root for proper import classification. Verify project structure. Test with various project configurations.

isort not found error when hook runs

Install isort with 'pip install isort' or 'pip install isort[black]' for Black profile support. Verify isort installation with 'isort --version'. Check Python environment and PATH. Test with various Python environments.

Import sorting changes break existing code

Review isort configuration and ensure --profile black is used for Black compatibility. Check for import side effects and verify import order doesn't affect functionality. Test with various import configurations.

autoflake removes type hints or annotations

Configure autoflake to preserve type hints with --remove-unused-variables but keep type annotations. Use --in-place flag carefully and review changes. Verify type hint preservation. Test with various type hint configurations.

Hook performance is slow on large Python files

Optimize hook script with timeout protection and file size checks. Consider excluding large files or using incremental processing. Verify file size limits. Test with various file sizes.

Source citations

Add this badge to your README

Show that Python Import Optimizer - Hooks is listed on HeyClaude. Paste this Markdown into your README — it renders the badge and links back to this page.

Listed on HeyClaude
[![Listed on HeyClaude](https://heyclau.de/badge/hooks/python-import-optimizer.svg)](https://heyclau.de/entry/hooks/python-import-optimizer)

How it compares

Python Import Optimizer - Hooks side by side with 3 alternatives on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.

Next steps differ across entries — use the actions in the table below to copy install commands and source links per resource.

Field

Automatically sorts and optimizes Python imports using isort when Python files are modified.

Open dossier

Detects unused CSS selectors when stylesheets are modified to keep CSS lean using PurgeCSS, PostCSS, and content analysis. This hook runs on CSS/SCSS file write/edit operations and analyzes stylesheets to identify unused selectors, generate optimized output, and report before/after size metrics.

Open dossier

A PostToolUse hook that reminds you to enable native query logging for PostgreSQL, Prisma, Sequelize, and TypeORM, and flags possible N+1 patterns when you edit SQL or data-access files.

Open dossier

A Claude Code SessionEnd hook that scans a project for dead code and writes a report to .claude/reports. It runs available tools per language: ESLint and Knip for JS/TS, autoflake or pylint for Python, Knip for unused npm dependencies, ripgrep for unreferenced src files, and jq to flag zero-coverage files.

Open dossier
Next stepsDiffers
Trust
Review statusReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewed
Package trustPackage not verifiedPackage not verifiedPackage not verifiedPackage not verified
Source provenanceSource-backedSource-backedSource-backedSource-backed
Submitter
Install riskReview firstReview firstReview firstReview first
Notes Safety Privacy Safety Privacy Safety Privacy Safety Privacy
Brand
Categoryhookshookshookshooks
Sourcesource-backedsource-backedsource-backedsource-backed
AuthorJSONboredJSONboredJSONboredJSONbored
Added2025-09-192025-09-192025-10-192025-10-19
Platforms
Claude Code
Claude Code
Claude Code
Claude Code
Source repo
Safety notesRuns automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.Runs automatically after bash, write, or edit activity and inspects files that look like query, model, repository, DAO, or SQL files. Creates .claude/logs/query-performance.log and appends database command or file-analysis events. Uses grep-based heuristics for query warnings and should not be treated as proof of a performance defect.Registered as a SessionEnd hook, so it runs automatically every time a Claude Code session ends. Invokes external tools via npx (ts-prune, Knip, eslint) and locally installed binaries (autoflake, pylint, vulture, jq, rg), which can trigger package downloads and execute project tooling. Defaults to DRY_RUN=true and only writes a report; setting DRY_RUN=false is intended to enable destructive cleanup, so review the report before changing it. Creates directories under .claude/backups and .claude/reports in the working tree.
Privacy notesReceives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.Reads query-related source files and may print file paths, query patterns, and database command strings to local hook output. Stores analyzed file paths and database command text in .claude/logs/query-performance.log. Database command text may include connection names, database names, or other operational details if typed directly into the command.Writes a dead-code report containing file paths, export names, and dependency names from the project to .claude/reports/dead-code-report.txt and echoes it to stderr. Running tools via npx may fetch packages from the npm registry over the network.
Prerequisites— none listed— none listed— none listed— none listed
Install
mkdir -p .claude/hooks && touch .claude/hooks/python-import-optimizer.sh && chmod +x .claude/hooks/python-import-optimizer.sh
mkdir -p .claude/hooks && touch .claude/hooks/css-unused-selector-detector.sh && chmod +x .claude/hooks/css-unused-selector-detector.sh
mkdir -p .claude/hooks && touch .claude/hooks/dead-code-eliminator.sh && chmod +x .claude/hooks/dead-code-eliminator.sh
Config
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/python-import-optimizer.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/css-unused-selector-detector.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/database-query-performance-logger.sh",
      "matchers": [
        "bash",
        "write",
        "edit"
      ]
    }
  }
}
{
  "hooks": {
    "sessionEnd": {
      "script": "./.claude/hooks/dead-code-eliminator.sh"
    }
  }
}
Citations
ClaimUnclaimedUnclaimedUnclaimedUnclaimed
Open 4 picks in the interactive comparison tool

Related guides

Signals

Loading live community signals…

More like this, weekly

A short, calm digest of reviewed Claude resources. Unsubscribe any time.