---
name: codeflash-import-audit
user-invocable: false
disable-model-invocation: true
description: >-
  Analyze Python import-time costs and identify slow imports. Activated when the user mentions
  "slow imports", "startup time", "import audit", "why does import take so long",
  "python -X importtime", "lazy loading", "defer imports", "import time optimization",
  or "reduce startup time".
allowed-tools: "Bash, Read, Grep, Glob"
---

# Import time audit

Analyze import-time costs for the module or package the user asked about.

## Step 1: Measure total import time

```bash
python -X importtime -c "import <target>" 2>&1 | head -1
```

This gives the total cumulative import time for the module.

## Step 2: Get the full import tree

```bash
python -X importtime -c "import <target>" 2>&1 | sort -t'|' -k2 -rn | head -30
```

The output format is: `import time: self [us] | cumulative | package.module`

## Step 3: Identify heavy imports

Parse the output and classify each import:

| Category | Threshold | Action |
|----------|-----------|--------|
| Heavy (>50ms cumulative) | Definitely defer | Lazy import or move to function scope |
| Medium (10-50ms) | Consider deferring | Lazy import if not used at module level |
| Light (<10ms) | Leave alone | Normal top-level import |

## Step 4: Check usage patterns

For each heavy import, use Grep to check if it's:
1. **Used at module level** (class definitions, decorators, type annotations) → harder to defer
2. **Used only in functions** → easy candidate for lazy loading
3. **Used in type annotations only** → use `from __future__ import annotations` + `TYPE_CHECKING`

## Step 5: Present findings

Show a ranked table:

| Import | Self (ms) | Cumulative (ms) | Used at module level? | Recommendation |
|--------|-----------|-----------------|----------------------|----------------|

End with specific code suggestions for the top 3-5 candidates:

```python
# Before
import heavy_module

# After (lazy)
def function_that_uses_it():
    import heavy_module
    ...
```

Or for type annotations:
```python
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
    import heavy_module
```

## Step 6: Estimate impact

Calculate the potential savings: sum of self-times for all deferrable imports. Report as:
- "Deferring N imports could save ~Xms of startup time (Y% of total)."
