Level: Advanced | Prerequisite: Week 8
Learning Goals
- Understand the structure of
pyproject.toml - Build and install your own package
- Provide CLI tools through
console_scripts - Virtual environment (
venv) - Upload to TestPyPI
1. Virtual Environment
Separate library versions for each project.
python -m venv .venv
#Activate
source .venv/bin/activate # macOS/Linux
.venv\Scripts\activate # Windows
#Terminate
deactivate
2. pyproject.toml
Standard configuration file for modern Python packages.
[project]
name = "mytool"
version = "0.1.0"
description = "My awesome CLI tool"
authors = [{name = "Hong Gil-dong", email = "[email protected]"}]
requires-python = ">=3.10"
dependencies = [
"requests>=2.28",
"rich>=13.0",
]
[project.scripts]
mytool = "mytool.cli:main"
[build-system]
requires = ["setuptools>=61"]
build-backend = "setuptools.build_meta"
3. Package Structure
mytool_project/
├── pyproject.toml
├── README.md
├── LICENSE
├── src/
│ └── mytool/
│ ├── __init__.py
│ └── cli.py
└── tests/
└── test_cli.py
# src/mytool/cli.py
def main():
print("Hello from mytool!")
Installation:
pip install -e . #Development Mode (Changes are Applied Immediately)
mytool #Run CLI
4. Build
pip install build
python -m build #Create .whl and .tar.gz in dist/
5. Upload to TestPyPI
pip install twine
twine upload --repository testpypi dist/*
Install in a different environment:
pip install --index-url https://test.pypi.org/simple/ mytool
6. requirements.txt vs pyproject.toml
| requirements.txt | pyproject.toml | |
|---|---|---|
| Purpose | Environment Pinning (deploy) | Library Metadata |
| Version | Exact Pin | Range |
| Build | Not supported | Supported |
pip freeze > requirements.txt #Export Current Environment
pip install -r requirements.txt #Reproduce
Key Examples (examples/)
| File | Content |
|---|---|
pyproject.toml |
Package configuration |
src/mytool/__init__.py |
Package |
src/mytool/cli.py |
CLI entry point |
README_PROJECT.md |
Package README example |
⚠️ Common Mistakes
- Not activating the virtual environment — Installed in system Python
- Omitting
__init__.py— Not recognized as a package - Not using
src/layout — Possible import conflicts - Redistribute without bumping version — PyPI rejects reuploading the same version
❓ FAQ
Q1. Don’t we use setup.py?
A. For new projects, use pyproject.toml. Only for legacy compatibility, use setup.py.
Q2. poetry vs pip+venv? A. Poetry is an integrated tool (dependency + virtual environment + build). For new projects, poetry or uv is recommended.
Q3. What's the difference between PyPI and TestPyPI? A. PyPI is the real public repository. TestPyPI is for practice.
📝 Exercises (exercises/)
exercise1.md— Package the results of the intermediate comprehensive practiceexercise2.md— Install console_scripts CLIexercise3.md— Upload to TestPyPI
Next Week
Week 10. Advanced Comprehensive Practice