Grimp
Grimp is a Python library (version 3.14) that builds a queryable graph of the imports within one or more Python packages. It provides tools for static analysis of import relationships and is actively maintained with regular updates for features and fixes.
Warnings
- gotcha Grimp performs static analysis and may not accurately reflect imports that are dynamically loaded (e.g., using `importlib` or conditional imports based on runtime conditions). Always verify results for complex import patterns.
- breaking The internal API structure, especially module paths for core functions like `build_graph_from_path` or `ImportGraph`, might change between major or even minor versions. Always consult the release notes when upgrading.
- gotcha Grimp's analysis relies on the Python environment it's run in. If analyzing code that targets a different Python version or has specific `sys.path` configurations, Grimp might not resolve imports correctly. Ensure your analysis environment matches the target project's setup.
Install
-
pip install grimp
Imports
- ImportGraph
from grimp.application.ports.import_graph import ImportGraph
- build_graph_from_path
from grimp.application.usecases import build_graph_from_path
Quickstart
import os
from grimp.application.usecases import build_graph_from_path
# Create a dummy package structure for demonstration
os.makedirs('my_package/submodule', exist_ok=True)
with open('my_package/__init__.py', 'w') as f: f.write('')
with open('my_package/module_a.py', 'w') as f: f.write('from .module_b import B')
with open('my_package/module_b.py', 'w') as f: f.write('from my_package.submodule import C')
with open('my_package/submodule/__init__.py', 'w') as f: f.write('')
with open('my_package/submodule/module_c.py', 'w') as f: f.write('import os')
# Build the import graph for 'my_package'
package_path = 'my_package'
package_name = 'my_package'
# NOTE: The exact function signature and import path might vary slightly.
# Refer to Grimp's official documentation for the precise quickstart.
try:
graph = build_graph_from_path(package_name, package_path)
print(f"Nodes in graph: {graph.modules()}")
print(f"Direct imports from module_a: {graph.direct_imports_for_module('my_package.module_a')}")
# Cleanup dummy files
import shutil
shutil.rmtree('my_package')
except ImportError as e:
print(f"Could not build graph, ensure grimp is installed and paths are correct: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")