How to Package and Publish Your Python Code to PyPI
Imagine you've written a fantastic recipe. Right now it only lives in your kitchen notebook. To share it with the world, you'd need to format it nicely, package it into a cookbook, and get it onto bookstore shelves.
Publishing a Python package follows the same idea. You take your working code, add some metadata (title, description, version), package it up, and upload it to PyPI - the Python Package Index. Once it's there, anyone in the world can install it with a simple pip install your-package.
In this tutorial, you'll learn the complete process: writing pyproject.toml, structuring your project for publishing, building distribution files, uploading to PyPI, and managing versions.
What Is pyproject.toml and Why Do You Need It?
Every published package needs a file that describes it - the name, version, author, and what other packages it depends on. In modern Python, that file is pyproject.toml.
Think of pyproject.toml as the label on a product at the store. It tells pip everything it needs to know: what the package is called, who made it, what version it is, and what other packages are required.
[build-system]
requires = ['setuptools>=68.0', 'wheel']
build-backend = setuptools.build_meta
[project]
name = my-awesome-tool
version = 1.0.0
description = A tool that does awesome things
authors = [{'name': 'Your Name', 'email': 'you@example.com'}]
license = MIT
requires-python = >=3.8
dependencies = ['requests>=2.25', 'click>=8.0']The [build-system] section tells pip which tool to use for building your package. The [project] section contains all the metadata that shows up on PyPI when people search for your package.
pyproject.toml [project] fields:
name
The package name on PyPI (must be unique)
version
Current version number (e.g., 1.0.0)
description
One-line summary shown in search results
readme
Path to README file (shown on PyPI page)
license
Software license (MIT, Apache, GPL, etc.)
requires-python
Minimum Python version needed
dependencies
List of packages yours depends on
classifiers
Categories for PyPI search filtering
urls
Links to homepage, docs, source codeHow Should You Structure a Project for Publishing?
A publishable Python project follows a specific layout. Getting this right from the start saves headaches later.
my-awesome-tool/
pyproject.toml # Package metadata
README.md # Description (shown on PyPI)
LICENSE # Legal stuff
src/
my_awesome_tool/ # Your actual package
__init__.py # Package init (sets __version__)
core.py # Main functionality
utils.py # Helper functions
tests/
test_core.py # Tests for core.py
test_utils.py # Tests for utils.pyThe src/ layout (putting your package inside a src/ folder) is recommended because it prevents a subtle bug. Without it, Python might accidentally import your local source code instead of the installed package during testing.
Contents of __init__.py: """My Awesome Tool - does awesome things.""" __version__ = "1.0.0" __author__ = "Your Name" from .core import main_function from .utils import helper_function Why this matters: - __version__ lets users check: my_awesome_tool.__version__ - Imports make the API clean: from my_awesome_tool import main_function
How Do You Build a Python Package?
Building a package means converting your source code into a format that pip can install. There are two formats: a source distribution (sdist) and a wheel (bdist_wheel).
A source distribution is like shipping raw ingredients - the user's machine compiles anything that needs compiling. A wheel is like shipping a ready-to-eat meal - it's pre-built and installs much faster.
Build process:
Install build tool:
$ pip install build
Build the package:
$ python -m build
This creates:
$ dist/my_awesome_tool-1.0.0.tar.gz (sdist)
And also:
$ dist/my_awesome_tool-1.0.0-py3-none-any.whl (wheel)
Wheel filename breakdown:
package: my_awesome_tool
version: 1.0.0
python: py3
abi: none
platform: any# .tar.gz file
# Contains raw source code
# May need to compile C extensions
# Slower to install
# Works everywhere as fallback# .whl file (actually a zip)
# Pre-built, ready to install
# No compilation needed
# Installs much faster
# Preferred by pipHow Do You Upload Your Package to PyPI?
Once your package is built, you upload it to PyPI using a tool called twine. Think of twine as the delivery truck that takes your packaged product to the store shelves.
Upload to PyPI workflow:
Step 1: Install the upload tool
$ pip install twine
Step 2: Verify package files are valid
$ twine check dist/*
Step 3: Test on TestPyPI first!
$ twine upload --repository testpypi dist/*
Step 4: Test the install from TestPyPI
$ pip install --index-url https://test.pypi.org/simple/ my-awesome-tool
Step 5: Upload to real PyPI
$ twine upload dist/*You'll need an account on pypi.org and an API token for authentication. Twine will ask for your credentials, or you can configure them in a .pypirc file.
After publishing, your package gets:
PyPI page:
https://pypi.org/project/my-awesome-tool/
Install command:
pip install my-awesome-tool
README:
Rendered as the project page
Version history:
All uploaded versions are listed
Download stats:
Track how many people install it
Anyone can now install your package with:
$ pip install my-awesome-toolHow Should You Version Your Python Package?
Version numbers aren't just random digits - they communicate important information to your users. The most common system is Semantic Versioning (SemVer), which uses three numbers: MAJOR.MINOR.PATCH.
Semantic Versioning Guide:
PATCH (1.0.0 -> 1.0.1)
Bug fixes, no new features, safe to upgrade
MINOR (1.0.0 -> 1.1.0)
New features added, backwards compatible
MAJOR (1.0.0 -> 2.0.0)
Breaking changes, may require code updates
Example version history:
v0.1.0 - Initial development release
v0.2.0 - Added new feature
v0.2.1 - Fixed a bug
v1.0.0 - First stable release!
v1.1.0 - Added CSV export feature
v1.1.1 - Fixed CSV encoding bug
v2.0.0 - Redesigned API (breaking change)Special version suffixes: 1.0.0a1 Alpha release (early testing) 1.0.0b1 Beta release (feature complete, still testing) 1.0.0rc1 Release candidate (almost ready) 1.0.0 Final stable release 1.0.0.post1 Post-release (docs fix, no code change) 1.1.0.dev1 Development version (work in progress)
Practice Exercises
These exercises test your understanding of packaging concepts, version management, and the publishing workflow.
Write a function called create_metadata(name, version, description) that returns a dictionary with three keys: 'name', 'version', and 'description', mapped to the corresponding arguments. Also include a key 'requires-python' with value '>=3.8' and a key 'license' with value 'MIT'.
The code below compares two version strings (like '1.2.3') to determine which is newer. There's a bug causing wrong results. Fix it so compare_versions correctly returns 'newer', 'older', or 'equal'.
Read the code below that simulates building distribution files for a package. What will it print?
The code below bumps version numbers using repetitive if/elif blocks. Refactor it into a clean function called bump_version(version, part) where part is 'major', 'minor', or 'patch'. The function should return the new version string. When bumping major, reset minor and patch to 0. When bumping minor, reset patch to 0.
Create a class called ReleaseManager that manages package releases:
__init__(self, name, version): Store the package name and version (a string like '1.0.0'). Initialize an empty list called releases.bump(self, part): Bump the version by part ('major', 'minor', or 'patch'). When bumping major, reset minor and patch to 0. When bumping minor, reset patch to 0. Store the new version as self.version.release(self): Append a dictionary {'version': self.version, 'files': [sdist, wheel]} to self.releases, where sdist is 'name-version.tar.gz' and wheel is 'name-version-py3-none-any.whl' (replace hyphens with underscores in the name for filenames). Print Released name version.history(self): Print each release on its own line in the format v{version}: {file1}, {file2}.