Python26 min read
Python Packaging
Learn how to package Python code so others can install it with pip, reuse your modules cleanly, and publish projects to PyPI like professional libraries.
David Miller
July 27, 2025
4.6k189
Packaging means converting your project into a reusable installable library.
Purpose:
- share code across projects
- publish on PyPI
- make installation easy: pip install yourpackage
## Recommended project structure
```
mypackage/
├── mypackage/
│ ├── __init__.py
│ └── module.py
├── tests/
├── README.md
├── LICENSE
└── pyproject.toml
```
Note: modern Python uses **pyproject.toml** (recommended).
## Minimal pyproject.toml (modern standard)
```toml
[build-system]
requires = ["setuptools>=68", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "mypackage"
version = "0.1.0"
description = "A short description"
readme = "README.md"
requires-python = ">=3.9"
dependencies = ["requests>=2.25.0"]
```
## __init__.py (clean exports)
```python
from .module import function1, function2
__all__ = ["function1", "function2"]
__version__ = "0.1.0"
```
## Build package
```bash
pip install build twine
python -m build
```
This creates files in `dist/`:
- .whl (wheel)
- .tar.gz (source)
## Upload to PyPI
```bash
twine upload --repository testpypi dist/*
# then real PyPI:
twine upload dist/*
```
## Install package
```bash
pip install mypackage
pip install -e . # editable install for development
```
## Graph: packaging lifecycle
```mermaid
flowchart LR
A[Write reusable code] --> B[Add pyproject.toml]
B --> C[Build dist/]
C --> D[Upload to PyPI]
D --> E[Others install with pip]
```
## Remember
- Packaging makes code reusable
- Use pyproject.toml (modern)
- Always include README and LICENSE
- Test on TestPyPI first
#Python#Advanced#Packaging