Auto-detect and trim unused Python imports and dependencies
Project description
PyTrim
A Python tool for trimming of unused imports and dependencies from Python projects. PyTrim helps keep your codebase clean by automatically removing unused dependencies from both source code and configuration files.
Features
- Auto-Detection: Automatically finds unused dependencies without manual specification
- Multi-format Support: Handles Python files, requirements.txt, pyproject.toml, setup.py, poetry.lock, Pipfile, YAML files, Docker files, and more
- Intelligent Analysis: Uses AST parsing to accurately identify unused imports and dependencies
- Modular Architecture: Clean, extensible design with separate extractors and removers for different file types
- CLI Interface: Easy-to-use command line interface with smart defaults
- Report Generation: Creates detailed Markdown reports of changes
- Git Integration: Automatic branch creation and PR generation
- Professional Package: Ready for PyPI distribution with proper setup and documentation
Installation
Docker (Recommended for most users)
-
Install Docker
Follow the official instructions to install Docker on your system: https://docs.docker.com/engine/install/ -
Navigate to Your Project's Source Code Directory
In your terminal, change to the root directory of the source code you want to analyze.cd /path/to/your/source
-
Run the PyTrim Container
This command will download the official PyTrim image from Docker Hub, start a container, and mount your local project directory into the container's/projectworkspace.# For Linux and macOS docker run --rm -it -v "$(pwd):/project" karakatsanis/pytrim
# For Windows (PowerShell) docker run --rm -it -v "${PWD}:/project" karakatsanis/pytrim
Important: Make sure to replace
/path/to/your/sourcewith the full, absolute path to the project directory you want to analyze.
PyPI
pip install pytrim
Note: Call graph analysis (the default detection method) requires the external tool PyCG. For the simplest experience with all features enabled, we recommend using the Docker image.
Install PyCG (optional)
When pytrim is installed from Pypi or source code, to run unused packages detection with call graph you need to install pycg.
- Install PyCG from source:
git clone https://github.com/gdrosos/PyCG.git && \ cd PyCG && \ pip3 install .
- Ensure the PyCG entrypoint is in PATH:
For the change to be permanent, add the following line to your shell's configuration file (e.g.,
~/.bashrc,~/.zshrc):export PATH="$HOME/.local/bin:$PATH"
After saving the file, restart your terminal or runsource ~/.bashrc(or your respective config file) to apply the changes.
Usage
After installation, use the pytrim command:
pytrim [-h] [-f FILE] [-d DIRECTORY] [-u UNUSED_IMPORTS [UNUSED_IMPORTS ...]] [-r] [-o] [-pr] [-dp | -fd] [-v] [-V]
[-gm [GENERATE_MAPPINGS ...]] [-mf MAPPINGS_FILE] [-e EXCLUDE [EXCLUDE ...]]
[project]
Options
-h, --help: Show help message and exit-f FILE, --file FILE: Process a single Python file-d DIRECTORY, --directory DIRECTORY: Process all.pyfiles in a directory-u UNUSED_IMPORTS [...], --unused-imports UNUSED_IMPORTS [...]: List of unused imports/dependencies to remove (optional - will auto-detect if not specified)-r, --report: Generate reports about trimmed packages in thepytrim_reportsfolder-o, --output: Create new debloated files in folderpytrim_outputinstead of overwriting originals-pr, --pull-request: Create a Git branch and GitHub Pull Request with changes-V, --version: Show version information-v, --verbose: Show detailed information about the trimming process.-dp, --deptry: Use deptry to find unused imports (requires deptry installed).-fd, --fawltydeps: Use fawltydeps to find unused dependencies (requires fawltydeps installed).-gm, --generate-mappings: Generate import mappings JSON file for specified packages (or use discovered packages if none specified), then run the full PyTrim analysis using the generated mappings.-mf, --mappings-file MAPPINGS_FILE: Use custom import mappings JSON file instead of built-in mappings.-e, --exclude: Exclude specific dependencies from the removal process.E.g. a transitive dependency that needs its version pinned.PROJECT: Project root directory (default: current directory)
Examples
Show help and all available options:
pytrim --help
Trim current project:
pytrim
Auto-detect unused dependencies and remove them from a project:
pytrim path/to/project/
Remove unused imports from a single file:
pytrim -f src/main.py -u os sys pandas
Process all Python files in a directory:
pytrim -d src/ -u requests json numpy
Trim current project with reporting:
pytrim -r
Auto-detect specific project with reporting:
pytrim project/ -r
Clean an entire project with specific packages:
pytrim project/ -u pandas matplotlib seaborn -r
Create a Pull Request for current project:
pytrim -pr
Output Modes
Default Mode
Files are modified in place. Only files that need changes are updated.
Output Mode (-o, --output)
Creates new debloated files in the pytrim_output/ directory instead of overwriting the original files.
Report Mode (-r, --report)
Generates detailed Markdown reports in the pytrim_reports/ directory with analysis of trimmed packages and dependencies.
Pull Request Mode (-pr, --pull-request)
- Files modified in place
- Creates Git branch with timestamp (format:
debloat/YYYYMMDDHHMMSS) - Generates
project_report.mdin project root - Automatically creates GitHub Pull Request with the changes (requires
ghCLI) - Requirements: Git repository,
gitandghCLI tools installed
Combined Modes
You can combine output modes:
-r -o: Generate reports AND save debloated files topytrim_output/-r -pr: Generate reports AND create pull request- All modes can be combined as needed
Development
For development setup, contributing guidelines, and architecture details, see CONTRIBUTING.md.
Requirements
- Python 3.10+
git- Required for version control operationsghCLI - Required for pull request creation (-prflag)
License
MIT License - see LICENSE file for details.
Contributing
Contributions are welcome! Please see CONTRIBUTING.md for development setup, contribution guidelines, and project architecture details.
Support
- Issues: GitHub Issues
- Source Code: GitHub
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file pytrim-0.2.0.tar.gz.
File metadata
- Download URL: pytrim-0.2.0.tar.gz
- Upload date:
- Size: 151.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.10.18
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e6a550f024b7b143ec594be6d9678f7fe7ac23f1562f2eb8fefd00d2b7aa4533
|
|
| MD5 |
6d44a6c27eb44d2b31dc4b02cade93fc
|
|
| BLAKE2b-256 |
4a8ee6f270e620e6c75b2daead4bc2f0fb8ce5d7121cf49100c4df2fd7330357
|
File details
Details for the file pytrim-0.2.0-py3-none-any.whl.
File metadata
- Download URL: pytrim-0.2.0-py3-none-any.whl
- Upload date:
- Size: 166.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.10.18
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3f0eb4393e71b9635e53381562307c87e1dbb13653e3766af360a9bf57af3bab
|
|
| MD5 |
572f826a17a90d128eb7f3429c3fc286
|
|
| BLAKE2b-256 |
7d312c2a973fd5a854c22c4763e8e48f331781fcf642ecf9584fa6ce1930514d
|