In this lesson, you will learn how to package your Python project into standardized distribution formats that can be easily installed by others via pip.
Now that your project is configured with a pyproject.toml file and follows standard layout conventions, you are ready to prepare it for distribution. To share your code, you need to bundle it into two specific formats: the Source Distribution (sdist) and the Wheel (bdist_wheel).
The Two Pillars of Distribution
- Source Distribution (sdist): This is a
.tar.gzarchive containing your source code, thepyproject.tomlfile, and any necessary metadata. It is the "raw" version of your project. When a user installs from an sdist,pipmay need to build the package on their machine, which requires a build backend to be present. - Wheel (bdist_wheel): This is a
.whlfile, which is a pre-built binary format. It contains the code exactly as it will appear when installed. Installing a wheel is significantly faster because it bypasses the build process, making it the preferred format for most users.
Building with build
To create these artifacts, we use the build module, which provides a standard, secure way to invoke your chosen build backend (like flit, hatchling, or setuptools). You can run it directly from your terminal within your project root:
python -m build
When you run this command, build reads your pyproject.toml, creates an isolated virtual environment to ensure your build-time dependencies are met, and then generates both the sdist and the wheel.
You will see a new dist/ directory appear in your project folder containing your newly minted files:
my_project-1.0.0.tar.gz(The source distribution)my_project-1.0.0-py3-none-any.whl(The built wheel)
These files are now ready to be uploaded to the Python Package Index (PyPI) or a private repository. They encapsulate everything pip needs to know to install your project correctly, including dependencies and entry points.
Key Takeaway: Use the build module to generate both a source distribution and a wheel, ensuring your package is compatible with both modern binary installation methods and fallback source builds.