A Python code analysis and visualization tool that generates dependency graphs for Python codebases. It parses every file with Python's ast module, maps import relationships between your own modules, the standard library and third-party libraries, detects I/O operations (with line numbers) from a built-in database of 122 patterns, and draws a color-coded dependency graph that starts from the entry file you choose.
- Static code analysis with AST parsing. No code is executed.
- Dependency tracking between custom modules, standard-library modules and external libraries.
- I/O operation detection: 122 patterns across about 40 libraries and standard-library modules, each hit recorded with its line number.
- Function/class usage tracking: calls and attribute accesses are mapped back to their source module through the alias table (
import pandas as pdβpd.read_csvis recorded aspandas.read_csv). - Dependency graph of the chosen main file, followed recursively through local modules, with color-coded nodes, edge labels and a legend.
- Web GUI (Streamlit) with a step-by-step workflow, plus a command-line interface that takes arguments.
- Exports: JSON analysis results, a detailed text report for the main file, and a 300 DPI PNG of the graph (GUI).
- Codebase statistics: totals plus top-5 lists of the largest files, most-imported modules and I/O-heavy files.
- Configurable exclusions for directories and files, and an editable list of "pre-built" libraries.
- Error handling: syntax errors, encoding errors and unreadable files are reported per file and skipped, so one bad file doesn't stop the analysis.
-
First pass: import analysis (top-level statements of each file)
- Direct imports:
import module - Aliased imports:
import module as alias - From imports:
from module import item - Relative imports:
from . import item - Star imports:
from module import * - Future imports:
from __future__ import feature - Builds the alias map used for usage tracking.
- Direct imports:
-
Second pass: function and I/O analysis (the whole tree via
ast.walk)- Finds function calls and attribute accesses.
- Maps each call to its source module using the alias map.
- Matches calls against the I/O pattern database (plus special cases such as
open(),Path(...).open()andDataLoader(...)). - Records each I/O operation with its line number.
Algorithm: RecursiveDependencyGraph
Input: main_file, dependency_store, prebuilt_libs
Output: directed graph G
1. Initialize empty directed graph G
2. Add main_file as the root node (yellow, square)
3. For each import in the current file:
a. Try to map the module to a local file (root-level, then relative to the importing file)
b. If found (custom module):
add a red node and recurse into that file's imports
c. Else if it is a stdlib module or listed in prebuilt_libs.txt:
add a green node
d. Else:
add a purple node (unresolved)
4. Add an edge from each dependent to its dependency
5. Track visited nodes so circular imports do not loop forever
6. Shell layout with the main file at the center
The pattern database in analyzer.py (_is_io_operation) contains 122 patterns:
open(),gzip.open,bz2.open,lzma.open,io.open,io.StringIO,io.BytesIO,io.TextIOWrapper
- Pandas:
read_csv,read_json,read_excel,read_parquet,read_feather,read_hdf,read_sql,read_html,read_xml, and the matchingto_*writers - NumPy:
load,save,loadtxt,savetxt,fromfile,tofile,genfromtxt - PyTorch:
load,save,load_state_dict,save_state_dict,DataLoader - Scikit-learn / joblib:
load_svmlight_file,joblib.load,joblib.dump
- JSON:
load,dump,loads,dumps - Pickle:
load,dump,loads,dumps - CSV:
reader,writer,DictReader,DictWriter - YAML:
safe_load,dump,safe_dump - TOML:
load,dump,loads,dumps - ConfigParser:
read,write
- SQLite:
sqlite3.connect - SQLAlchemy:
create_engine - Requests:
get,post,put,delete - urllib:
urllib.request.urlopen,urllib.request.urlretrieve
- Pathlib:
Path.open,read_text,write_text,read_bytes,write_bytes,mkdir,rmdir,unlink,touch - Shutil:
copy,copy2,copyfile,copytree,move,rmtree - Zipfile:
ZipFile,PyZipFile,open - Tarfile:
open,TarFile - Rarfile:
RarFile,RarFile.extract
- Images:
PIL.Image.open,PIL.Image.save,cv2.imread,cv2.imwrite - Audio:
librosa.load,librosa.output.write_wav - HDF5:
h5py.File,h5py.Group.create_dataset,h5py.Dataset.read - Excel:
openpyxl.load_workbook,openpyxl.Workbook.save - XML:
xml.etree.ElementTree.parse/write,lxml.etree.parse/write - PDF:
PyPDF2.PdfReader,PyPDF2.PdfWriter.write
- AWS:
boto3.client - Google Cloud:
google.cloud.storage.Client - Azure:
azure.storage.blob.BlobServiceClient
- Matplotlib:
pyplot.savefig,pyplot.imsave - Plotly:
io.write_html,io.write_image - Seaborn:
savefig - Altair:
save,renderer.save - Streamlit:
file_uploader,download_button
| File | Role |
|---|---|
analyzer.py |
AST parsing and analysis engine: imports, function usage, I/O detection |
dependency_store.py |
Stores per-file results, computes summary statistics and analytics, saves/loads JSON |
worker.py |
Walks the codebase, prints the report, builds and draws the main-file dependency graph |
gui.py |
Streamlit web interface with step-by-step workflow |
non_interactive_main.py |
Command-line entry point |
prebuilt_libs.txt |
Library names treated as "pre-built" (green nodes). Edit to taste. |
DependencyStore = {
"files": {file_path: {
"imports": [module_names],
"io_count": int,
"function_usage": {module: [functions]}
}},
"modules": {module_name: [dependent_files]},
"io_operations": {file_path: [operations_with_line_numbers]},
"function_usage": {file_path: {module: [functions]}},
"file_info": {file_path: {
"path": str,
"size": int,
"lines": int,
"empty": bool
}},
"summary": {
"total_files": int,
"total_imports": int,
"total_io_operations": int,
"total_lines": int,
"empty_files": int
}
}get_summary(): overall statistics for the codebaseget_files_with_io(): files containing I/O operationsget_largest_files(limit): largest files by line countget_most_imported_modules(limit): most frequently imported modulesget_files_by_io_count(limit): files with the most I/O operationsget_file_io_operations(file_path): I/O operations of one fileget_file_info(file_path): file metadata and statisticsget_module_dependents(module): files that import a module
- Node types:
- π‘ Yellow square: main entry file
- π΄ Red circle: custom/local module
- π’ Green circle: standard-library module or a library listed in
prebuilt_libs.txt - π£ Purple circle: unresolved module (not local, not stdlib, not in
prebuilt_libs.txt)
- Layout: shell layout with the main file at the center
- Edge labels:
dependent --> dependency(names shortened to 4 characters) - Legend explaining colors and edge labels
- Export: 300 DPI PNG from the GUI
- Python 3.10+ (uses
sys.stdlib_module_names) streamlit,networkx,matplotlib,numpy(seerequirements.txt)
git clone https://github.com/virkha-kumari/python_codeflow_graph_maker.git
cd python_codeflow_graph_maker
pip install -r requirements.txtRun everything from the repository folder, because prebuilt_libs.txt and output_files/ are resolved relative to the working directory.
streamlit run gui.pyA step-by-step flow: pick a folder (type the path, or use the tkinter folder picker on a desktop session), choose the main file, set exclusions, run the analysis, view the graph and statistics, then export the JSON, the text report and the 300 DPI PNG.
python non_interactive_main.py path/to/codebase path/to/codebase/main.py --exclude-dir tests --exclude-dir docsPrints the per-file analysis, summary statistics, graph nodes and edges, and writes the JSON and text report to output_files/. It does not save the graph image (use the GUI for the PNG).
| Argument | Meaning |
|---|---|
codebase_path |
Root folder of the codebase to analyze |
main_file |
Entry-point .py file (absolute, or relative to codebase_path) |
--exclude-dir NAME |
Directory name to skip (repeatable). venv, .git, __pycache__ are always skipped. |
--exclude-file NAME |
File name to skip (repeatable) |
Example on this repo itself:
python non_interactive_main.py . gui.pyThe full DependencyStore structure above, saved as output_files/dependencies_<folder>.json.
Saved as output_files/detailed_deps_<folder>.txt:
- Dependency relationships of the main file, with module types
- I/O operations of the main file, with line numbers
- Analysis summary (files, imports, I/O operations, lines, empty files)
- Per-file imports, I/O operations with line numbers, and function usage by module
- Analysis summary and top-5 lists for the largest files, most-imported modules and I/O-heavy files
- Color-coded dependency graph with legend and edge labels
- 300 DPI PNG export (GUI)
The two files committed in output_files/ are demo output results, produced by running the tool on this repo itself (main file gui.py). They are kept so you can see what to expect before running anything:
output_files/dependencies_python_codeflow_graphmaker.json: the JSON dump of the analysisoutput_files/detailed_deps_python_codeflow_graphmaker.txt: the text report
The absolute paths inside them (D:\Projects\python_codeflow_graphmaker\...) are from the author's machine and are left as they are on purpose. Your own run will show your own paths. New output written to output_files/ is gitignored, so your results are not committed by accident.
- Run from the repository folder (for
prebuilt_libs.txtandoutput_files/). - Only
.pyand.pywfiles are analyzed. - Module-to-file resolution relies on file and folder names.
- Source files are syntactically valid Python. Files that aren't are reported and skipped.
- Source files are UTF-8. Files that aren't are reported and skipped.
- The graph covers the dependencies of one main file, not the whole codebase at once.
- Dynamic imports (
importlib.import_module,__import__) and imports built from strings are not detected. - Imports inside functions, classes or
if/tryblocks are not recorded (only top-level imports are). - Static analysis only. Runtime behavior is not observed.
- Dependencies of external packages are not followed.
- The graph is a static matplotlib figure. Large graphs get crowded.
- Behavior on very large codebases (1000+ files) is untested.
- No automated test suite yet. It has been run on small projects, including itself.
- Relative imports with complex parent-directory structures may resolve incorrectly.
- Module aliasing in complex scenarios.
- Some edge cases in star-import analysis.
- Limited support for namespace packages.
Add entries to the io_patterns set in _is_io_operation() in analyzer.py:
io_patterns = {
# Add your custom patterns here
"your_library.read_data",
"your_library.save_data",
# ... existing patterns
}Add library names to prebuilt_libs.txt, one per line, to have them drawn as green nodes.
Colors are set in graph_maker() in worker.py (yellow, red, green, purple) and can be changed there.
- Python
astmodule: static code analysis - NetworkX: graph construction and layout
- Matplotlib: graph rendering and PNG export
- Streamlit: web interface
None yet. Add one before reusing the code.
Made with β€οΈ for the Python community. If something doesn't work, please open an issue!