7 min read
•Question 39 of 41hardPython Packaging
Creating distributable packages.
Python Packaging
Project Structure
code.txtTEXT
my_package/
├── src/
│ └── my_package/
│ ├── __init__.py
│ ├── module.py
│ └── subpackage/
│ └── __init__.py
├── tests/
│ └── test_module.py
├── pyproject.toml
├── README.md
└── LICENSEpyproject.toml
code.txtINI
[build-system]
requires = ["setuptools>=61.0", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "my-package"
version = "1.0.0"
description = "A sample package"
readme = "README.md"
license = {text = "MIT"}
requires-python = ">=3.8"
authors = [{name = "Your Name", email = "you@example.com"}]
dependencies = ["requests>=2.28.0", "numpy>=1.21.0"]
[project.optional-dependencies]
dev = ["pytest>=7.0", "black", "mypy"]
[project.scripts]
my-cli = "my_package.cli:main"
[project.urls]
Homepage = "https://github.com/you/my-package"Building and Publishing
$ terminalBash
# Install build tools
pip install build twine
# Build package
python -m build
# Creates dist/my_package-1.0.0.tar.gz
# Creates dist/my_package-1.0.0-py3-none-any.whl
# Upload to PyPI
twine upload dist/*
# Install locally for development
pip install -e .Entry Points
code.pyPython
# src/my_package/cli.py
def main():
print("Hello from CLI!")
if __name__ == "__main__":
main()Virtual Environments
$ terminalBash
# Create venv
python -m venv venv
# Activate
source venv/bin/activate # Linux/Mac
venv\Scripts\activate # Windows
# Install dependencies
pip install -r requirements.txt
# Generate requirements
pip freeze > requirements.txt