Instantly map, visualize, and analyze import dependencies in any Python project.
- The Problem
- The Solution
- Features
- Quick Start
- Installation
- Usage
- Real-World Results
- Advanced Features
- How It Works
- Use Cases
- Integration
- Testing
- Troubleshooting
- Documentation Links
- Contributing
- License
- Credits
Understanding import dependencies in Python codebases is critical but painful:
- Circular imports cause mysterious
ImportErrorat runtime, and tracing the chain manually through files is tedious - Coupling creep happens silently β one module gradually becomes depended on by everything, making refactoring dangerous
- Dead code hides in plain sight β modules that nothing imports waste maintenance effort
- Architecture drift is invisible β without a dependency map, you can't tell if your clean layers are still clean
- Code reviews miss structural issues because reviewers focus on logic, not import topology
Result: Hours wasted debugging import errors, surprise breakages during refactoring, and codebases that slowly become unmaintainable.
DepMapper scans any Python project and gives you instant visibility into your dependency structure:
- Scan all Python files and build a complete dependency graph
- Visualize the dependency tree in your terminal or as a Graphviz diagram
- Detect circular imports automatically with precise chain reporting
- Measure coupling metrics (fan-in, fan-out, instability) for every module
- Find orphan modules that nothing imports (potential dead code)
- Generate comprehensive reports in text, JSON, or Markdown format
One command. Full visibility. Zero dependencies.
python depmapper.py report ./my_projectReal Impact:
- Circular import debugging: 30+ minutes β 3 seconds
- Coupling analysis: manual spreadsheet β instant metrics
- Dead code discovery: hours of grep β one command
| Feature | Description |
|---|---|
| π Full Project Scanning | Recursively scans all .py files with smart exclusions |
| π³ Dependency Tree | ASCII-art tree visualization of import relationships |
| π Circular Import Detection | DFS-based cycle finder with precise chain reporting |
| π Coupling Metrics | Fan-in, fan-out, and instability index per module |
| π» Orphan Detection | Find modules with no inbound imports |
| π Multi-Format Reports | Text, JSON, and Markdown output |
| π Graphviz DOT Export | Generate visual dependency graphs |
| π§ CLI + Python API | Use from terminal or integrate programmatically |
| π« Zero Dependencies | Pure Python standard library β nothing to install |
| π₯οΈ Cross-Platform | Windows, Linux, macOS β works everywhere |
| π¦ Package-Aware | Handles __init__.py, relative imports, nested packages |
| β‘ Fast | Scans 100+ files in under a second |
git clone https://github.com/DonkRonk17/DepMapper.git
cd DepMapperpython depmapper.py scan ./your_projectpython depmapper.py circular ./your_projectpython depmapper.py report ./your_projectThat's it! No installation, no dependencies, no configuration. Just Python 3.7+.
git clone https://github.com/DonkRonk17/DepMapper.git
cd DepMapper
python depmapper.py --versionDepMapper is a single file! Just copy depmapper.py to your project:
cp DepMapper/depmapper.py /your/project/tools/
python tools/depmapper.py scan ./srccd DepMapper
pip install -e .
depmapper --version- Python 3.7+ (uses
dataclasses,typing,ast) - No external dependencies β 100% Python standard library
- Any OS β Windows, Linux, macOS
DepMapper provides 7 commands, each focused on a specific analysis:
Scan and display a summary of the project structure.
python depmapper.py scan ./my_projectOutput:
[OK] Scan complete: /path/to/my_project
Files: 14 | Modules: 14 | Dependencies: 10 | Time: 0.015s
Options:
--exclude DIRSβ Comma-separated directories to skip--jsonβ Output full scan data as JSON--markdownβ Output full scan data as Markdown
Visualize import relationships as an ASCII tree.
python depmapper.py tree ./my_projectOutput:
main
|-- utils
| `-- config
`-- database
|-- models
`-- config [circular]
Options:
--module NAMEβ Start tree from a specific module--depth Nβ Limit tree depth (default: 10)
Detect and report all circular import chains.
python depmapper.py circular ./my_projectOutput (when cycles found):
[!] Found 2 circular import chain(s):
Cycle 1: config -> database -> config
Cycle 2: auth -> users -> permissions -> auth
Output (clean project):
[OK] No circular imports detected!
Exit codes: 0 = clean, 2 = cycles found (useful in CI/CD)
Calculate fan-in, fan-out, and instability for every module.
python depmapper.py metrics ./my_project --sort fan_inOutput:
COUPLING METRICS
----------------------------------------------------------------------
Module Fan-In Fan-Out Instab.
----------------------------------------------------------------------
config 8 0 0.000 [stable]
utils 6 2 0.250
models 4 3 0.429
main 0 5 1.000 [!]
Options:
--sort FIELDβ Sort byinstability,fan_in,fan_out, orname--jsonβ Output as JSON
Interpreting instability:
- 0.0 = Maximally stable β many modules depend on it, it depends on nothing
- 1.0 = Maximally unstable β depends on everything, nothing depends on it
- 0.8+ marked with
[!]β watch for excessive dependencies
Identify modules with no inbound imports.
python depmapper.py orphans ./my_projectOutput:
ORPHAN MODULES (3 found)
--------------------------------------------------
main (entry point / orchestrator)
setup (standalone / potential dead code)
old_migration (standalone / potential dead code)
Generate a comprehensive report combining all analyses.
python depmapper.py report ./my_project
python depmapper.py report ./my_project --json
python depmapper.py report ./my_project --markdown -o report.mdOptions:
--jsonβ JSON format--markdownβ Markdown format--output FILEβ Save to file instead of stdout
Generate a visual dependency graph in DOT format.
python depmapper.py graph ./my_project -o deps.dot
dot -Tpng deps.dot -o deps.png # Render with GraphvizOptions:
--output FILEβ Save DOT to file--no-highlightβ Don't highlight circular import edges in red
Use DepMapper programmatically in your own scripts or tools:
from depmapper import DepMapper
# Initialize
dm = DepMapper()
# Scan a project
result = dm.scan("./my_project")
print(f"Found {result.total_files} files, {len(result.modules)} modules")
# Get dependency tree
tree = dm.get_tree()
print(tree)
# Find circular imports
cycles = dm.find_circular()
if cycles:
print(f"WARNING: {len(cycles)} circular imports!")
for cycle in cycles:
print(" -> ".join(cycle))
# Coupling metrics
metrics = dm.get_metrics(sort_by="instability")
for m in metrics:
print(f"{m.module}: fan_in={m.fan_in}, fan_out={m.fan_out}, "
f"instability={m.instability:.3f}")
# Find orphan modules
orphans = dm.find_orphans()
print(f"Orphans: {orphans}")
# Query specific modules
imports = dm.get_imports_for("main")
importers = dm.get_importers_of("utils")
classified = dm.get_all_imports("main")
# Generate reports
text_report = dm.generate_report(format="text")
json_report = dm.generate_report(format="json")
md_report = dm.generate_report(format="markdown")
# Generate Graphviz DOT
dot = dm.generate_dot(highlight_cycles=True)| Task | Manual Time | Method |
|---|---|---|
| Find circular import chain | 30+ minutes | Trace imports through files |
| Assess coupling health | 1-2 hours | Create spreadsheet manually |
| Find dead code modules | 45+ minutes | grep + manual checking |
| Architecture review | 2+ hours | Read every file's imports |
| Task | DepMapper Time | Command |
|---|---|---|
| Find circular import chain | 3 seconds | depmapper circular ./src |
| Assess coupling health | 3 seconds | depmapper metrics ./src |
| Find dead code modules | 3 seconds | depmapper orphans ./src |
| Architecture review | 5 seconds | depmapper report ./src |
[OK] Scan complete: AutoProjects/SynapseLink
Files: 14 | Modules: 14 | Dependencies: 10 | Time: 0.015s
Circular imports: 0 [OK]
Orphans: 13 (mostly entry points/test scripts)
Most stable module: synapselink (fan_in=10, instability=0.000)
Skip specific directories:
python depmapper.py scan ./project --exclude "tests,docs,migrations"Pipe into jq, load in scripts, integrate with CI/CD:
python depmapper.py metrics ./src --json | python -c "
import json, sys
data = json.load(sys.stdin)
unstable = [m for m in data if m['instability'] > 0.8]
if unstable:
print(f'WARNING: {len(unstable)} highly unstable modules')
sys.exit(1)
"Add to your build pipeline:
# Fail build if circular imports exist
python depmapper.py circular ./src
# Exit code 2 = cycles found, 0 = cleanGenerate beautiful dependency diagrams:
python depmapper.py graph ./src -o deps.dot
dot -Tpng deps.dot -o deps.png
dot -Tsvg deps.dot -o deps.svgCircular import edges are highlighted in red by default.
dm = DepMapper()
dm.scan("./project")
# What does main.py import?
dm.get_imports_for("main")
# -> ['config', 'database', 'utils']
# What imports config.py?
dm.get_importers_of("config")
# -> ['main', 'database', 'utils', 'auth']
# Classify all imports in a module
dm.get_all_imports("main")
# -> {'stdlib': ['os', 'sys'], 'local': ['config', 'utils'],
# 'third_party': ['requests'], 'relative': []}depmapper.py (single file, ~850 LOC)
βββ Data Classes
β βββ ImportInfo - Single import statement
β βββ ModuleInfo - Single Python module (file)
β βββ CouplingMetrics - Per-module coupling data
β βββ ScanResult - Complete scan output
βββ DepMapper Engine
β βββ scan() - Parse files, build graph
β βββ get_tree() - ASCII tree visualization
β βββ find_circular() - DFS cycle detection
β βββ get_metrics() - Fan-in/fan-out/instability
β βββ find_orphans() - No-inbound-import modules
β βββ generate_report()- Multi-format reports
β βββ generate_dot() - Graphviz export
βββ CLI Interface
βββ 7 subcommands via argparse
-
AST Parsing: Uses Python's
astmodule to parse source files and extractImportandImportFromnodes β no regex, no fragile text matching. -
Import Resolution: Resolves imports to local modules by checking against the discovered module set. Handles absolute imports, relative imports (
.,..), and package__init__.pyfiles. -
Stdlib Filtering: Maintains a comprehensive set of 150+ Python stdlib module names to exclude from the local dependency graph.
-
Cycle Detection: Uses depth-first search with path tracking. When a node is revisited on the current DFS path, a cycle is extracted and normalized (starts from the lexicographically smallest module).
-
Instability Metric: Based on Robert C. Martin's metric:
I = Ce / (Ca + Ce)where Ca = fan-in (afferent coupling), Ce = fan-out (efferent coupling)- Range: 0.0 (maximally stable) to 1.0 (maximally unstable)
- Single file: Easy to copy, no package structure needed
- Zero dependencies: Works on any machine with Python 3.7+
- AST over regex: Accurate parsing, handles all import styles
- Graph as adjacency dict: Simple, fast, memory-efficient for typical project sizes
- Separate scan/analyze: Scan once, run multiple analyses
Before refactoring, understand what depends on what:
python depmapper.py metrics ./src --sort fan_in
# High fan-in modules = change carefully, many things depend on themPrevent circular imports from entering your codebase:
# In your CI pipeline
python depmapper.py circular ./src || exit 1Generate a dependency report for PR reviews:
python depmapper.py report ./src --markdown -o DEPENDENCY_REPORT.mdKeep architecture docs in sync with actual dependencies:
python depmapper.py graph ./src -o docs/dependencies.dot
dot -Tsvg docs/dependencies.dot -o docs/dependencies.svgFind modules that nothing imports:
python depmapper.py orphans ./src
# Standalone modules with no fan-out = likely dead codeDepMapper integrates with the Team Brain tool ecosystem:
With CodeMetrics:
# Combine dependency analysis with code health metrics
from depmapper import DepMapper
dm = DepMapper()
dm.scan("./project")
metrics = dm.get_metrics()
# Cross-reference with CodeMetrics LOC/complexity dataWith SynapseLink:
# Alert team to circular imports
from synapselink import quick_send
from depmapper import DepMapper
dm = DepMapper()
dm.scan("./project")
cycles = dm.find_circular()
if cycles:
quick_send("TEAM", "Circular imports detected!", str(cycles))With AgentHealth:
# Track dependency health over time
from depmapper import DepMapper
dm = DepMapper()
dm.scan("./project")
report = dm.generate_report(format="json")
# Log to AgentHealth for trend analysisFull integration documentation:
- INTEGRATION_PLAN.md β Comprehensive integration strategy
- QUICK_START_GUIDES.md β 5-minute guides per agent
- INTEGRATION_EXAMPLES.md β Copy-paste code patterns
DepMapper includes a comprehensive test suite with 56 tests across 10 test classes:
python test_depmapper.py| Category | Tests | Status |
|---|---|---|
| Core Scanning | 13 | All passing |
| Dependency Tree | 5 | All passing |
| Circular Import Detection | 4 | All passing |
| Coupling Metrics | 4 | All passing |
| Orphan Detection | 2 | All passing |
| Report Generation | 4 | All passing |
| DOT Graph Generation | 3 | All passing |
| Utility Methods | 4 | All passing |
| Edge Cases | 11 | All passing |
| CLI Interface | 6 | All passing |
| TOTAL | 56 | 100% passing |
Tests cover: core functionality, edge cases (empty files, syntax errors, encoding issues, deep nesting), error handling, all output formats, all CLI commands, data classes, and API methods.
"Path not found" error:
[X] Error: Path not found: ./my_project
- Check the path exists and is spelled correctly
- Use absolute paths if relative paths aren't working
- On Windows, use forward slashes or escaped backslashes
No dependencies found:
[OK] Scan complete: ...
Files: 10 | Modules: 10 | Dependencies: 0
- Your project's local imports may use different names than the file paths
- Check if your modules are using standard
import module_namesyntax - Third-party imports are not shown (only local project dependencies)
Parse errors reported:
[!] 2 file(s) had parse errors
- Some Python files have syntax errors β DepMapper skips these gracefully
- Run
python -c "import ast; ast.parse(open('file.py').read())"to check specific files - Parse errors don't affect analysis of other files
Windows encoding issues:
- DepMapper automatically handles Windows console encoding
- If you see garbled output, ensure your terminal supports UTF-8
- Windows: Fully supported. Uses Path objects for cross-platform paths.
- Linux: Fully supported. All features work.
- macOS: Fully supported. All features work.
| Document | Description |
|---|---|
| README.md | This file β primary documentation |
| EXAMPLES.md | 10+ detailed usage examples |
| CHEAT_SHEET.txt | Quick reference for terminal |
| INTEGRATION_PLAN.md | Team Brain integration strategy |
| QUICK_START_GUIDES.md | 5-minute guides per agent |
| INTEGRATION_EXAMPLES.md | Copy-paste integration patterns |
| branding/BRANDING_PROMPTS.md | DALL-E branding prompts |
Contributions are welcome! To contribute:
- Fork the repository
- Create a feature branch:
git checkout -b feature/my-feature - Make your changes following the code style:
- Type hints on all functions
- Docstrings for all public methods
- ASCII-only in Python code (no emoji)
- Cross-platform compatibility
- Run the test suite:
python test_depmapper.py - Ensure 100% tests passing
- Submit a pull request
- Type hints: Required for all function signatures
- Docstrings: Google-style, required for all public functions/classes
- Imports: Standard library only, alphabetical order
- No Unicode in code: Use
[OK],[X],[!]instead of emoji - Cross-platform: Use
pathlib.Path, not hardcoded paths
MIT License β see LICENSE for full text.
Built by: ATLAS (Team Brain) For: Logan Smith / Metaphy LLC Initiative: ToolForge Session β Priority 3 Creative Tool Why: Enable instant visibility into Python dependency structures, replacing hours of manual import tracing with one-command analysis Part of: Beacon HQ / Team Brain Ecosystem Date: February 14, 2026
Technical Highlights:
- 850+ lines of production Python code
- 56 comprehensive tests (100% passing)
- Zero external dependencies
- 7 CLI commands + full Python API
- 3 output formats (text, JSON, Markdown)
- Graphviz DOT export for visual diagrams
- Cross-platform (Windows, Linux, macOS)
Special Thanks:
- The Team Brain collective for the tool ecosystem
- Robert C. Martin for the instability metric concept
- Python
astmodule maintainers for reliable source parsing
Built with precision, deployed with pride. Team Brain Standard: 99%+ Quality, Every Time.