Python Packaging: Managing Package Files, Compiling Extension Modules When Building a Wheel, and Uploading to PyPI
Managing Package Files
When creating a Python package, the location of files depends on your project structure.
Basic pyproject.toml Configuration
1 | |
Single Python File (or Extension Module) as Module
1 | |
This single-file module will be copied into the site-packages directory during installation.
⚠️ This layout makes it difficult to include non-.py or non-extension data files (e.g., .json, .html). If you need to include such resources, use the folder-as-module approach described below.
Folder as Module
1 | |
Each subfolder intended as a submodule must include an __init__.py file (even if empty).
Configure pyproject.toml:
1 | |
To include non-.py or non-extension data files (e.g., configs, templates):
1 | |
Compiling Extension Modules When Building a Wheel
To compile extension modules when building a wheel, implement a custom setuptools build_ext command.
Project Structure
1 | |
Custom build_ext Command (your_package/_build_ext_command.py)
1 | |
pyproject.toml Configuration
1 | |
If BuildExtCommand requires third-party libraries (e.g., pybind11), declare them under [build-system]:
1 | |
Uploading to PyPI
Install Required Tools
First, install build and twine:
1 | |
Build the Package
Run the following command in your project's root directory:
1 | |
This generates .tar.gz and .whl files in the dist/ folder.
Upload to PyPI
Use twine to upload your package. Navigate to the dist/ directory and run:
1 | |
You'll be prompted for your PyPI API token. Refer to the official PyPI documentation for details.
Verify Publication
After uploading, check PyPI to see if your package is listed: https://pypi.org/
Search for your package name-it may take a few minutes to appear.