Skip to main content
Editor

How to Package and Publish Your Python Code to PyPI

Intermediate25 min5 exercises75 XP
0/5 exercises

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.

Anatomy of a pyproject.toml file
# Let's look at a typical pyproject.toml structure:
# (This is TOML format, not Python - we're simulating it)
pyproject = {
'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'],
},
}
print('[build-system]')
for key, val in pyproject['build-system'].items():
print(f' {key} = {val}')
print('\n[project]')
for key, val in pyproject['project'].items():
print(f' {key} = {val}')
Output
[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.

Important pyproject.toml fields
# Key fields in [project] and what they do:
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 code',
}
print('pyproject.toml [project] fields:\n')
for field, desc in fields.items():
print(f' {field}')
print(f' {desc}\n')
Output
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 code

How Should You Structure a Project for Publishing?

A publishable Python project follows a specific layout. Getting this right from the start saves headaches later.

Recommended project layout for PyPI
# The recommended project structure for publishing:
layout = '''
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.py
'''
print(layout)
Output

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.py

The 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.

Setting up __init__.py for publishing
# What goes in __init__.py for a published package:
# Typically you set the version and import key items:
init_content = '''
"""My Awesome Tool - does awesome things."""
__version__ = "1.0.0"
__author__ = "Your Name"
from .core import main_function
from .utils import helper_function
'''
print('Contents of __init__.py:')
print(init_content)
print('Why this matters:')
print('- __version__ lets users check: my_awesome_tool.__version__')
print('- Imports make the API clean: from my_awesome_tool import main_function')
Output
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.

Building and understanding distribution files
# Building your package (terminal commands):
build_steps = [
('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)'),
]
print('Build process:\n')
for label, cmd in build_steps:
print(f' {label}:')
print(f' $ {cmd}\n')
# Let's understand the wheel filename:
wheel_name = 'my_awesome_tool-1.0.0-py3-none-any.whl'
parts = wheel_name.replace('.whl', '').split('-')
labels = ['package', 'version', 'python', 'abi', 'platform']
print('Wheel filename breakdown:')
for label, part in zip(labels, parts):
print(f' {label}: {part}')
Output
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
Source Distribution (sdist)
# .tar.gz file
# Contains raw source code
# May need to compile C extensions
# Slower to install
# Works everywhere as fallback
Wheel (bdist_wheel)
# .whl file (actually a zip)
# Pre-built, ready to install
# No compilation needed
# Installs much faster
# Preferred by pip

How 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.

Uploading to PyPI with twine
# Upload workflow:
upload_steps = [
('1', 'pip install twine', 'Install the upload tool'),
('2', 'twine check dist/*', 'Verify package files are valid'),
('3', 'twine upload --repository testpypi dist/*', 'Test on TestPyPI first!'),
('4', 'pip install --index-url https://test.pypi.org/simple/ my-awesome-tool',
'Test the install from TestPyPI'),
('5', 'twine upload dist/*', 'Upload to real PyPI'),
]
print('Upload to PyPI workflow:\n')
for num, cmd, desc in upload_steps:
print(f' Step {num}: {desc}')
print(f' $ {cmd}\n')
Output
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.

What happens after you publish
# What happens after a successful upload:
post_upload = {
'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',
}
print('After publishing, your package gets:\n')
for feature, detail in post_upload.items():
print(f' {feature}:')
print(f' {detail}\n')
print('Anyone can now install your package with:')
print(' $ pip install my-awesome-tool')
Output
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-tool

How 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.

Understanding Semantic Versioning
# Semantic Versioning: MAJOR.MINOR.PATCH
versioning_rules = {
'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',
}
print('Semantic Versioning Guide:\n')
for change, meaning in versioning_rules.items():
print(f' {change}')
print(f' {meaning}\n')
# Version progression example:
versions = [
('0.1.0', 'Initial development release'),
('0.2.0', 'Added new feature'),
('0.2.1', 'Fixed a bug'),
('1.0.0', 'First stable release!'),
('1.1.0', 'Added CSV export feature'),
('1.1.1', 'Fixed CSV encoding bug'),
('2.0.0', 'Redesigned API (breaking change)'),
]
print('Example version history:')
for ver, desc in versions:
print(f' v{ver} - {desc}')
Output
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)
Pre-release and special versions
# Pre-release and development versions:
special_versions = [
('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)'),
]
print('Special version suffixes:\n')
for ver, meaning in special_versions:
print(f' {ver:15s} {meaning}')
Output
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.

Build Package Metadata
Write Code

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'.

def create_metadata(name, version, description):
# Return the metadata dictionary
pass
Fix the Version Comparator
Fix the Bug

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'.

def compare_versions(v1, v2):
'''Compare v1 to v2. Returns newer, older, or equal.'''
parts1 = v1.split('.')
parts2 = v2.split('.')
for i in range(max(len(parts1), len(parts2))):
p1 = parts1[i] if i < len(parts1) else '0'
p2 = parts2[i] if i < len(parts2) else '0'
if p1 > p2:
return 'newer'
elif p1 < p2:
return 'older'
return 'equal'
print(compare_versions('1.0.0', '1.0.0'))
print(compare_versions('2.0.0', '1.0.0'))
print(compare_versions('1.10.0', '1.9.0'))
print(compare_versions('1.0.0', '1.0.1'))
Predict the Build Output
Predict Output

Read the code below that simulates building distribution files for a package. What will it print?

def build_package(name, version):
safe_name = name.replace('-', '_')
sdist = f'{safe_name}-{version}.tar.gz'
wheel = f'{safe_name}-{version}-py3-none-any.whl'
return sdist, wheel
packages = [
('my-tool', '1.0.0'),
('data_utils', '0.2.1'),
]
for name, ver in packages:
sdist, wheel = build_package(name, ver)
print(f'dist/{sdist}')
print(f'dist/{wheel}')
Refactor the Version Bumper
Refactor

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.

# Messy version bumping code - refactor this!
version = '1.2.3'
parts = version.split('.')
major = int(parts[0])
minor = int(parts[1])
patch = int(parts[2])
# Bump major
new_major = f'{major + 1}.0.0'
print(f'Major bump: {new_major}')
# Bump minor
new_minor = f'{major}.{minor + 1}.0'
print(f'Minor bump: {new_minor}')
# Bump patch
new_patch = f'{major}.{minor}.{patch + 1}'
print(f'Patch bump: {new_patch}')
Build a Release Manager
Write Code

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}.
  • class ReleaseManager:
    # Build your release manager
    pass

    Related Tutorials

    Was this tutorial helpful?