All in One View

Content from Introduction


Last updated on 2026-10-27 | Edit this page

Overview

Questions

  • What is software packaging and why should researchers care about it?
  • How does packaging make software easier to share, install and maintain?
  • What information is typically included in a software package?
  • How are software dependencies managed in modern Python projects?
  • What is uv and how does it fit into the modern Python packaging ecosystem?
  • What is pyproject.toml and why has it become the standard project configuration file?
  • What is the difference between a source distribution and a wheel?
  • How are Python packages published and distributed?

Objectives

  • Explain what software packaging is and why it is important for software reuse, reproducibility and sustainability.
  • Describe the key components of a Python package and the role of package metadata, dependencies and documentation.
  • Distinguish between traditional and modern Python packaging tools and standards, including setup.py, pip, pyproject.toml, lock files and uv.
  • Explain how package managers help manage dependencies and create reproducible software environments.
  • Describe the difference between source distributions (sdists) and wheels.

Introduction


Many researchers write code, install software libraries and share their scripts with collaborators. However, fewer people understand how packages are created, how dependencies are managed or how to make software easy for others to install and reuse.

Understanding packaging helps us move from writing code that works on our machine to developing software that others can reliably install, use, reproduce and contribute to.

In this session we will look into what software packaging entails and why should we care about packaging. In the practical part of this session, we will explore modern Python packaging and package management using uv, a fast Python package manager and project management tool that is rapidly becoming popular across the Python community.

What is a software package?


A package is more than just code - in may contain a number of components:

  • Source code – modules, functions and classes that implement the software’s functionality.
  • Project/software metadata – information that describes the software project, such as its name, version, authors, description, homepage and supported Python versions. This information helps users and package repositories identify and manage the package.
  • Dependency information – a list of the external libraries and packages required for the software to run correctly, along with any version constraints.
  • Licensing information – the software licence that defines how others can use, modify and redistribute the software (for example, MIT, BSD or GPL).
  • Documentation – information that helps users understand how to install, use and contribute to the software. This often includes a README, user guides, API documentation and examples.
  • Tests – special code that verifies the software behaves as expected and helps developers identify bugs when making changes.
  • Build instructions – configuration information (often part of documentation) that tells packaging tools how to build or install the software.
  • Optional assets such as data files, images or compiled extensions.

Packages provide a way of bundling these components into an easy to transport artefact (“archive”) - that can be more easily distributed and installed.

Packages are used in almost all programming languages, operating systems and computing environments to simplify the process of installing and managing software.

Why packaging software matters?


Let’s start with a familiar situation. Imagine you have written a useful analysis script in Python and a colleague wants to use it. You send them the code and they immediately encounter problems:

  • Which version of Python should they use?
  • Which libraries need to be installed?
  • Which versions of those libraries are compatible with one another?
  • How can they reproduce your software environment?

This is where packaging becomes important - it provides one standard way distribute and install your code on other people’s machines.

Packaging provides a number of important benefits.

Packaging makes software distribution more efficient as it promotes a modular approach to software development and code reuse - reducing duplication. Applications and libraries typically include only the code that is specific to them, while shared external dependencies can be installed separately and reused across multiple projects. By not including copies of all the external code it uses - software distribution becomes more efficient.

Packaging helps ensure that software can be shared, reused and reproduced by others. Packaging captures important information about dependencies, versions and installation requirements, making it easier for collaborators to run your software and obtain consistent results. Good packaging practices also support software sustainability by making projects easier to maintain, distribute and build upon over time.

Dependencies, virtual development environments and packages


We cannot talk about software packaging without covering dependency management and development environments.

Dependency management and software packaging are closely related but serve different purposes.

Dependency management focuses on identifying, installing and maintaining the external packages that the software relies on - making sure that all the external libraries required by the software are available and compatible. Dependency management is useful even if your software is never distributed as a package (because it will almost always rely on a number of external dependencies that you will have to manage on your system).

Next step is to capture this dependency information (dependencies and their versions) for your software project’s environment somehow so others (or yourself on another machine) can replicate that. Dependency information can be recorded manually (e.g. just describing them as a list) but it is not very practical as software often relies on dozens or hundreds of external packages. Such lists, if not managed by special tools, quickly become out of date.

Dependency information for your software can then used to recreate a virtual (reproducible) software environment for your code on any machine (in theory). This is a mechanism of isolating the environment for developing and running a software project (containing the specified dependencies) from other projects on the same machine.

Packaging goes a step further by preparing the software for distribution (e.g. via PyPI or other software registries), bundling the code, software metadata, dependency information and other supporting files into into a distributable and installable artefact (“archive”).

Modern tools such as uv combine these capabilities for Python, making it easy to manage dependencies while also building and distributing packages (and uploading them to a shared package repository).

By contrast, more traditional tools such as pip and venv each address a specific part of the workflow: pip manages installation of Python packages, while venv creates isolated Python environments, requiring multiple tools to accomplish what uv provides through a single interface.

Python packaging and dependency management tool ecosystem


The Python packaging and dependency management ecosystem is rich but can also be complicated and, at times, confusing. Different tools address different aspects of the software development workflow. Some tools focus solely on installing packages (such as pip), others create isolated Python environments (such as venv), while modern tools like uv, poetry and hatch combine package installation, dependency management, environment management and packaging into a single workflow.

If you’d like to explore the ecosystem in more detail, “Python dependency management is a dumpster fire” guide provides a comprehensive overview of dependency management in Python.

We are mostly going to focus on packaging tools but will unavoidably mention dependency and environment management tools too.

Traditional tools & methods

Historically, many researchers created Python packages using a combination of the following tools.

Pip

pip is Python’s traditional package installer. It allows users to install packages from package repositories such as PyPI, as well as from local directories, archives or source code repositories such as GitHub.

While pip remains the standard installer included with standard Python distribution, newer tools are increasingly combining package installation, environment management and dependency resolution into a single workflow.

Setup.py

For many years, setup.py file (which exists at the root of a software project directory) was the primary mechanism for defining how a Python package (contained in that directory) should be built and installed. It contains information about the package, including its name, version, dependencies and build instructions.

setup.py is a Python file, the presence of which is an indication that the module/package you are about to install has likely been packaged and distributed with setuptools, which is the traditional standard for distributing Python modules. Invoking Python setup.py script directly is now deprecated, but setup.py is still a valid setuptools configuration file.

Alternatively, if you run:

BASH

$ pip install .

from the software project directory root, pip will use information in setup.py to install the software package.

Below is an example setup.py from Pythonhosted’s “Getting Started With setuptools and setup.py” guide. Recall that the content of setup.py is just Python code.

PYTHON

import os
from setuptools import setup

# Utility function to read the README file.
# Used for the long_description.  It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(
    name = "an_example_pypi_project",
    version = "0.0.4",
    author = "Andrew Carter",
    author_email = "andrewjcarter@gmail.com",
    description = ("An demonstration of how to create, document, and publish "
                                   "to the cheese shop a5 pypi.org."),
    license = "BSD",
    keywords = "example documentation tutorial",
    url = "http://packages.python.org/an_example_pypi_project",
    packages=['an_example_pypi_project', 'tests'],
    long_description=read('README'),
    classifiers=[
        "Development Status :: 3 - Alpha",
        "Topic :: Utilities",
        "License :: OSI Approved :: BSD License",
    ],
)

While still supported by many projects, modern Python packaging has moved away from relying directly on setup.py in favour of other standardised configuration files, such as pyproject.toml.

Setuptools

setuptools is one of the oldest and most widely used Python packaging tools. It extends Python’s original package management tool called distutils and provides functionality for building, packaging and distributing software. distutils is now officially abandoned and has been removed entirely from the Python standard library as of Python 3.12.

One of the main advantages of setuptools over distutils is that it allows you to specify dependencies for your package, so that other packages that your package depends on will be automatically installed when your package is installed. This makes it easier to distribute your package, because users don’t have to manually install the dependencies before installing your package.

setuptools also provides tools for creating and managing Python virtual environments, which are isolated Python environments that allow you to have multiple versions of the same package installed on the same machine. This is useful for development and testing, because you can test your package in different environments without affecting other projects.

Many modern packaging tools still rely on setuptools behind the scenes, even when developers no longer interact with it directly.

Requirements.txt

A requirements.txt file provides a simple way to record project’s dependency information. It is commonly used to specify the packages and versions needed to recreate a virtual software environment (e.g. using pip).

Although still used, many modern Python projects now manage dependencies and development environment through pyproject.toml and lock files (to be covered soon).

Below is an example requirements.txt for the software project we will use in examples in this lesson. requirements.txt is a plain text file which records dependencies (one per line) and locks their versions installed in the current virtual development environment (it acts as a basic lock file).

contourpy==1.3.3
coverage==7.12.0
cycler==0.12.1
fonttools==4.60.1
iniconfig==2.3.0
kiwisolver==1.4.9
matplotlib==3.10.7
numpy==2.3.5
packaging==25.0
pandas==2.3.3
pillow==12.0.0
pluggy==1.6.0
Pygments==2.19.2
pyparsing==3.2.5
pytest==9.0.1
pytest-cov==7.0.0
python-dateutil==2.9.0.post0
pytz==2025.2
six==1.17.0
tzdata==2025.2

Modern tools & methods

Python packaging has evolved significantly over time. Modern package managers help by:

  • Tracking dependencies
  • Resolving version conflicts
  • Creating reproducible environments
  • Recording exact package versions

pyproject.toml

The introduction of pyproject.toml file (written in TOML format) has been one of the most significant developments in Python packaging. It provides a standard location for:

  • Project metadata
  • Dependencies
  • Build configuration
  • Tool-specific settings

Instead of maintaining information across multiple files, projects can now define most packaging-related configuration in a single location. This standardisation has simplified Python packaging considerably.

Modern Python projects increasingly adopt the following tools that manage packages described with pyproject.toml.

Lock files

A lock file records the exact versions of all dependencies used in a software environment. While a project’s pyproject.toml file specifies the packages that a project depends on, it often allows a range of compatible versions to be installed. As a result, two people installing the same project at different times may receive slightly different versions of the underlying dependencies.

A lock file removes this uncertainty by recording the precise version of every package that was resolved during installation, including indirect/transitive dependencies (dependencies of dependencies) that have not been explicitly declared anywhere in your project. This allows the same software environment to be recreated consistently across different machines and at different points in time.

For example, a project may specify a dependency on pandas >=2.0. Without a lock file, one user might install version 2.1 while another installs version 2.3. With a lock file, both users install exactly the same version that was originally tested with the project.

Modern package managers such as uv automatically generate and maintain lock files (e.g. uv.lock). These files play an important role in reproducible research by helping collaborators recreate the same software environment and reducing the risk of unexpected behaviour caused by dependency updates.

Callout

Fully reproducible environments

Remember, if two people create environments from a dependency definition file at different points in time, they could end up with different environments. One could work fine, while the other could be broken. And this could be caused by a broken release from some transitive dependency we did not even know we needed.

The lock file represents a fully reproducible environment (as long as packages and versions remain available in package repositories).

Thus, good dependency management boils down to a few steps:

  • Creating a dependency definition file (listing all direct dependencies)
  • Generating a lock file (explicit step of “locking” our direct and indirect dependencies)
  • Tracking both the definition file and the lock file in version control
  • Syncing our environment with the lock file

uv

Uv is a modern package and project management tool developed by Astral. It combines dependency management, virtual environment management and package installation into a single, high-performance tool.

With uv, dependencies are declared in pyproject.toml. uv automatically resolves compatible versions and records them in a “lock” file called uv.lock. The lock file ensures that collaborators can recreate the same software environment later. This is an important contribution to reproducibility.

Many common tasks that previously required several separate tools can now be performed through a single command-line interface. We will use uv tool in the practical part of this session.

Poetry

Poetry focuses on dependency management, reproducible environments and simplified package publishing. It introduced many of the ideas that influenced modern Python project management and remains popular in both industry and research.

Hatch

Hatch provides a flexible framework for managing Python projects, environments and package builds. It is particularly popular among developers who require more advanced build and release workflows.

Comparison of modern packaging tools

The above modern packaging tools are not competing packaging standards — they all work with the same underlying Python packaging standards. They mainly differ in the workflow and user experience they provide. A summary of their main characteristics is shown below.

Feature uv poetry hatch
Primary focus Fast package, dependency and project management Dependency management and package publishing Flexible project, environment and build management
Uses pyproject.toml ✅ ✅ ✅
Package installation ✅ ✅ ✅
Dependency management ✅ ✅ ✅
Virtual environment management ✅ Built in ✅ Built in ✅ Built in
Lock file support ✅ uv.lock ✅ poetry.lock ✅ It does not have a single, universally adopted default lock file
Build Python packages ✅ ✅ ✅
Publish packages ✅ ✅ ✅
Performance ⭐⭐⭐⭐⭐ Excellent - very fast (Rust implementation) ⭐⭐⭐ Good ⭐⭐⭐⭐ Very good
Learning curve Low Low–Moderate Moderate
Typical use General-purpose modern Python development Research and application development Advanced projects and library development
Adoption Rapidly growing Mature and widely adopted Mature, especially for library development
Best suited for Most new Python projects Existing projects and teams already using Poetry Developers who need flexible build configurations, multiple environments and advanced release workflows

Packaging and distribution formats


When discussing Python packaging, it is important to distinguish between source code, distributions and packages.

Source code

Source code contains the original project files created by the developer.

Source distribution (sdist)

A source distribution contains the original source code and all the files needed to build the package. Source distributions are typically distributed as compressed archives such as:

my_package-1.0.0.tar.gz

Installing from a source distribution requires the package to be built on the user’s machine. This provides maximum flexibility but may require additional build tools or compilers.

Wheel

A wheel is a built distribution format designed for fast installation. Wheel files typically have names such as:

my_package-1.0.0-py3-none-any.whl

Unlike source distributions, wheels can usually be installed directly without rebuilding the package. This makes installation faster and more reliable.

Most users install wheel packages without realising it because package managers automatically select a compatible wheel when one is available.

Concept What it is Typical contents Typical format When it’s used
Source code The original project files created by the developer. Python modules, pyproject.toml, README, tests, licence, documentation and configuration files. Project directory By developers during software development and maintenance.
Source distribution (sdist) A distributable archive containing the source code and everything needed to build the package. Source code, metadata, build configuration, documentation and other project files. .tar.gz Used by packaging tool (e.g. uv build) when the package needs to be built on the user’s machine or when distributing source code.
Wheel A pre-built distribution that is ready to install. Built package files and package metadata. .whl Used by package installers (e.g. uv, pip) for fast, reliable installation without rebuilding the package.

Package repositories


Once packages have been built, they are typically published to a package repository. Package repositories provide a central location where users can discover, download and install software.

The most widely used repository for publishing Python packages is the Python Package Index (PyPI), which hosts hundreds of thousands of open-source packages. While PyPI remains the standard and primary public package repository, it is not the only option. For example, GitHub can also be used to distribute packages, especially useful for private or organisation-managed software. Developers can attach source distributions and wheel files to GitHub Releases, allowing users to download and install specific versions directly. In addition, GitHub Packages provides a package hosting service that enables individuals and organisations to publish and manage Python packages alongside their source code repositories. This can be particularly useful for private projects or software intended for use within a specific organisation or research group.

Summary


Software packaging is a fundamental practice that helps make software easier to share, install, reuse and maintain.

We introduced the concepts behind software packaging, package structure, dependency management, packaging tools and distribution formats. We also covered why packaging and dependency management is important for sustainable research software and reproducible research, and provided an overview of the complex Python packaging and dependency management ecosystem.

Next we will exploring modern Python packaging workflows using uv in a practical session. It provides a single, modern interface for creating projects, managing dependencies, creating virtual environments and building packages. Its speed, simplicity and standards compliance make it an excellent choice for new Python projects, while still supporting the same packaging standards (pyproject.toml, wheels and source distributions) used by other modern tools.

Key Points

  • Software packaging bundles code, metadata, dependencies and documentation into a distributable artefact.
  • Packaging makes software easier to share, install, reuse and reproduce.
  • Python packages are commonly distributed as source distributions (sdists) or wheels.
  • Modern Python packaging is built around the pyproject.toml standard.
  • Package managers such as uv simplify dependency management, environment creation and package installation.
  • Lock files help create reproducible software environments by recording exact dependency versions.
  • Package repositories such as PyPI provide a central location for publishing and installing software.

Content from Example Code


Last updated on 2026-10-28 | Edit this page

Overview

Questions

  • How to install dependencies and set up virtual environment for a Python project using pip and venv

Objectives

  • Obtain and inspect the example code used for this lesson
  • Install dependencies and set up virtual environment for running and developing the code using pip and venv

For this lesson we’ll be using the example code that does spacewalks analysis available on GitHub, which we’ll clone onto our machines using the Bash shell.

Obtaining Example Code


Create your own copy of the spacewalks_example repository using Use this template button on GitHub.

Open a command-line shell (e.g. via Git Bash in Windows, bash shell on Linux or Terminal on a Mac) and navigate to where you would like the example code to reside (e.g. to your home directory).

Use Git to clone your copy of the spacewalks repository.

BASH

$ cd ~
$ git clone https://github.com/YOUR-GITHUB/spacewalks_example.git
$ cd spacewalks_example

The example code implements spacewalk data analysis - we will use this code to create a Python package using uv.

Examining the Code


Let’s take a look at the spacewalk analysis code, which is in the file called eva_data_analysis.py. Feel free to use your preferred editor of choice, such as Notepad, Nano or Visual Studio Code.

The code is designed to:

  • Read in the data from the JSON file
  • Change the data from one data format to another and saves to a file in the new format (CSV)
  • Perform some calculations to generate summary statistics about the data
  • Make a plot to visualise the data

A few things to note about the software project:

  • requirements.txt file in the project root lists the software dependencies - such as Pandas, Matplotlib, Pytest, MkDocs - and describes the software environment
  • data folder contains input data
  • results folder contains cleaned dataset converted to CSV format and the resulting plot
  • tests folder contains test code
  • site folder contains documentation compiled with MkDocs

Setting up the Environment


Before we can run the code, we need to create and activate a virtual environment called “.venv” from the root of the software project directory:

The active virtual environment is indicated in the command line prompt between the round brackets: “(.venv)”.

Next, we will install the necessary dependencies from the requirements.txt file using pip:

$ python -m pip install -r requirements.txt

To ensure the code is working correctly, run the tests using Pytest.

$ python -m pytest

Running the Code


To run the analysis using the eva_data_analysis.py script from the command line terminal, do:

$ python eva_data_analysis.py data/eva-data.json results/eva-data.csv

If the code runs successfully, you should get the resulting plot in results/cumulative_eva_graph.png.

Key Points

  • pip and venv are traditional tools for installing dependencies and setting up virtual environments for running and developing Python code.
  • requirements.txt file can be used to record and share a snapshot of the virtual environment.

Content from Software packaging with uv


Last updated on 2026-10-28 | Edit this page

Overview

Questions

  • How do I package a Python project with uv?
  • What project files does uv create/maintain and what are they used for?
  • What is pyproject.toml and why has it become the standard project configuration file?
  • How does uv manage dependencies and virtual environments?
  • What is a lock file and why is it important for reproducible software?
  • How do I add, remove and update project dependencies?
  • How can I run Python scripts using uv?
  • How do I build a source distribution and a wheel using uv?
  • How can I migrate an existing project from pip and venv to uv?

Objectives

  • Explain the role of uv in modern Python project development.
  • Migrate an existing pip/venv-based projects to a uv development workflow.
  • Manage project dependencies and understand the purpose of lock files.
  • Describe the structure and role of pyproject.toml as the central project configuration file.
  • Run Python commands and scripts using uv without manually managing virtual environments.
  • Build Python source distributions and wheel packages for distribution.

Introduction


uv is a multi-functional tool, that performs a number of tasks:

  • installs and manages Python versions,
  • installs and runs Python tools (Python packages which provide applications that can be used as command line tools) published as Python packages (e.g. ruff, pip, etc.),
  • provides comprehensive Python project and dependency management capabilities and handles virtual environments with a universal lock file,
  • runs Python scripts,
  • includes a pip-compatible interface for users with existing pip-based development workflows,
  • is really performant and much faster than pip.

The core uv software project development workflow looks like as follows:

  1. project creation and setup - uv can create a new project layout for you so you start with a clean structure instead of a blank folder
  2. virtual environments - uv manages virtual environments directly, which means you do not need to switch between different tools to create and activate environments
  3. dependency installation - uv installs packages quickly while still supporting the same dependency ecosystem you may already be familiar with
  4. running commands inside the environment - uv can run Python commands or scripts inside the environment without you having to manually activate it
  5. (optionally) package and publish your code.

uv - key files to know

uv uses a combination of the following files and directories in your project (which it keeps in sync with one another) to do its job:

  • pyptoject.toml file - to maintain the project’s metadata and configuration
  • .venv folder - to maintain the development environment
  • uv.lock file - to record (lock) the development environment.

uv project commands

There is a number of uv commands to handle Python projects as part of the development workflow (which manipulate and sync the files and directories above); we give a short summary below.

Callout

uv project commands

A summary of uv commands for creating and working on Python projects, i.e., with a pyproject.toml file.

  • uv init: create a new Python project (and start a new pyptoject.toml file).
  • uv add: add a dependency to the project (locking and syncing the environment).
  • uv remove: remove a dependency from the project (locking and syncing the environment).
  • uv sync: sync the project’s dependencies with the environment (i.e. into the .venv folder in the project directory).
  • uv lock: create a lock file for the project’s dependencies (i.e. “locking” the current environment).
  • uv run: run a Python command or a Python script in the project environment (automatically locking and syncing if anything is out-of-date).
  • uv tree: view the dependency tree for the project.
  • uv build: build the project into distribution archives.
  • uv publish: publish the project to a package index.

Project commands are a subset of all uv commands.

Check out the uv guides covering the full set of uv features.

Initialising a package with uv


Let’s go to our example spacewalks code.

This is an existing project where you currently use venv and pip tools to manage dependencies and environments. You want to migrate to using uv for your development workflow.

If you have not done it already, make a copy of example project repository into your GitHub account by using the Use this template button on GitHub. Next, clone your copy of the repository locally:

BASH

$ cd ~
$ git clone https://github.com/YOUR-GITHUB/spacewalks_example

Let’s navigate into the spacewalks_example project directory and examine it a bit.

BASH

$ cd spacewalks_example
$ ls -la
total 56
drwxr-xr-x   15 mbassan2  staff    480 23 Jul 17:21 .
drwx------@ 897 mbassan2  staff  28704 23 Jul 17:21 ..
drwxr-xr-x   12 mbassan2  staff    384 23 Jul 17:21 .git
-rw-r--r--    1 mbassan2  staff     26 23 Jul 17:21 .gitignore
-rw-r--r--    1 mbassan2  staff    721 23 Jul 17:21 CITATION.cff
drwxr-xr-x    3 mbassan2  staff     96 23 Jul 17:21 data
drwxr-xr-x    7 mbassan2  staff    224 23 Jul 17:21 docs
-rw-r--r--    1 mbassan2  staff   3991 23 Jul 17:21 eva_data_analysis.py
-rw-r--r--    1 mbassan2  staff   1090 23 Jul 17:21 LICENSE
-rw-r--r--    1 mbassan2  staff    296 23 Jul 17:21 mkdocs.yml
-rw-r--r--    1 mbassan2  staff   2009 23 Jul 17:21 README.md
-rw-r--r--    1 mbassan2  staff    805 23 Jul 17:21 requirements.txt
drwxr-xr-x    5 mbassan2  staff    160 23 Jul 17:21 results
drwxr-xr-x   12 mbassan2  staff    384 23 Jul 17:21 site
drwxr-xr-x    3 mbassan2  staff     96 23 Jul 17:21 tests

We can see the requirements.txt file used to record dependencies from the development environment.

To migrate from the existing development workflow to use uv, you need to use uv init first to initiate the project and get the basic pyptoject.toml file created.

From within project root, do:

BASH

$ uv init --name spacewalks
Callout

Using uv for new projects

If you are starting a brand new Python project then you can use uv straight away to replace all the other tools you may have used in the past in your development workflow.

For example, to create a new Python project called “hello-world” using the uv init command, do:

BASH

$ uv init hello-world
$ cd hello-world

This creates a directory called hello-world and a project with the same name. uv will create the following files and directories as a basic scaffolding for your Python project:

.
├── .git/
├── src/
│   └── hello-world/
│       └── __init__.py
├── .gitignore
├── .python-version
├── README.md
└── pyproject.toml

Running uv init in our existing project has added the following files and directories:

.
├── src/
│   └── spacewalks/
│       └── __init__.py
├── .python-version
└── pyproject.toml

The __init__.py Python file contains a simple “Hello world” program.

The .python-version file contains the project’s default Python version (based on what is installed on your machine). This file tells uv which Python version to use when creating the project’s virtual environment.

uv has also created a starter pyproject.toml file to store the metadata about your project.

TOML

[project]
name = "spacewalks"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
dependencies = []

pyproject.toml structure

pyproject.toml is a configuration file introduced by PEP 518 to standardise Python project setup. Written in TOML (Tom’s Obvious, Minimal Language), it serves as a single source of truth for your project’s build system, metadata, and tool configurations. It tells tools like uv, pip, poetry, or hatch how to construct your project.

Unlike the older setup.py approach, which contains executable Python code, pyproject.toml uses a declarative, static configuration format.

pyptoject.toml structure contains three main components (tables):

  • [build-system] table: defines the tools and other dependencies are needed to build your project’s source distribution and wheel (built distribution).
  • [project] table: stores metadata like your project’s name, version, and dependencies.
  • [tool] table: configures settings for development tools like linters or formatters.

The [build-system] table is not compulsory - you can use pyproject.toml just to store metadata and configuration. If your project is an application (i.e. not designed to be published as a package), you do not need a [build-system] table. You can initialise a project not designed to be published as a package by running uv init --no-package.

If you are building a package or library to be published, the [build-system] table is required so uv knows which build backend to use (e.g. uv_build, setuptools, hatch).

For example:

TOML

[build-system]
requires = ["uv_build>=0.11.31,<0.12"]
build-backend = "uv_build"

Or:

TOML

[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"

uv supports various build backends as specified by PEP 517, but also provides a native build backend uv_build that integrates tightly with uv to improve performance and user experience.

When you create a new project with uv init, the uv_build backend will be used by default. The uv_build backend has reasonable defaults and requires zero configuration for most users. You can use the uv build command to create the source distribution and wheel for your project.

The [tool] table has tool-specific subtables, e.g., [tool.uv], [tool.hatch], content of which are defined by each tool. You would need to consult the particular tool’s documentation to know what it can contain.

A minimal pyproject.toml just requires the [project] table.

Callout

pyproject.toml guide

pyproject.toml file can be used to declare many more configuration parameters about Python projects that we are not going into details here. A good guide on writing pyproject.toml files can be found from Python Packaging User Guides website.

Installing a package locally


A common convention is to keep Python code in a directory called src under the project root directory. The directory spacewalks represents the top-level package. The presence of an __init__.py file within spacewalks registers that directory as a package. The file __init__.py is run when the package is imported with import spacewalks.

Let us see this in action. First ensure the virtual environment is activated:

Then, launch a Python console:

BASH

$ python

Within the Python console, import the main function from spacewalks.

PYTHON

>>> from spacewalks import main
Traceback (most recent call last):
  File "<python-input-0>", line 1, in <module>
    from spacewalks import main
ModuleNotFoundError: No module named 'spacewalks'

This failed because our package is not installed in our virtual environment.

Exit the Python console with the exit() command and install our package with pip.

BASH

$ python -m pip install .

Now relaunch the Python console. Within the Python console, import the main function from spacewalks and execute it.

PYTHON

>>> from spacewalks import main
>>> main()
Hello from spacewalks!

Project scripts

By default, uv creates an entry in the project.scripts section of pyproject.toml.

TOML

[project.scripts]
spacewalks = "spacewalks:main"

This defines a command which gets installed in your environment when you install the package. Here, the command is spacewalks which invokes the main function in the spacewalks package namespace. Instead of launching the Python console, importing main from spacewalks, and running it, we can execute it with the following shell command:

BASH

$ spacewalks
Hello from spacewalks!

Running commands with uv


The uv run command can be used to run Python scripts or Python commands in your project environment. It precedes commands to be run with the latest build of your project and ensures the virtual environment contains the correct versions of project dependencies.

To see this in action, first delete the virtual environment we made earlier.

BASH

$ deactivate
$ rm -r .venv

Now, if we try to run the spacewalks command we get an error saying the command is not found. Instead, run spacewalks using the uv run command:

BASH

$ uv run spacewalks

uv creates a virtual environment (.venv/) and a lock file (uv.lock) the first time you run any project command, i.e., uv add, uv run, uv sync, or uv lock. The lock file contains details of all packages and their versions required by the project.

During every uv run invocation, uv will verify that the lock file is up-to-date with the pyproject.toml, and that the environment is up-to-date with the lock file, keeping your project in-sync without the need for manual intervention. uv run guarantees that your command is run in an environment with all required dependencies at their locked versions.

The project structure now looks like the following - with new parts added that all work together and allow uv to manage your project.

.
├── .git/
├── .venv/
├── data/
├── docs/
├── results/
├── site/
├── src/
├── .gitignore
├── .python-version
├── README.md
├── eva_data_analysis.py
├── pyproject.toml
└── uv.lock

The command uv run can also be used in place of the regular python command when running scripts. For example, to run the data analysis script:

BASH

$ uv run eva_data_analysis.py

However, we get the following import error:

OUTPUT

ModuleNotFoundError: No module named 'matplotlib'

This is because uv uses the pyproject.toml file to create the virtual environment and install our package. This file should contain a list of dependencies required for our code to run.

Callout

Manually updating the virtual environment

Alternatively, you can use uv sync to manually update .venv then activate it before executing a Python command or running your Python script:

Note: if you want to run scripts and commands using the Python command (i.e. without uv run) - the virtual environment must be active.

Managing dependencies with uv


Next, we need to install dependencies for our project, which are recorded in requirements.txt file. By looking at the code in eva_data_analysis.py Python script, we can tell we require matplotlib and pandas packages.

We can use the uv add command to install them:

BASH

$ uv add matplotlib pandas

Alternatively, we can use the uv add command with the -r flag to add all dependencies from the requirements.txt file in a single go.

BASH

$ uv add -r requirements.txt

You can also specify version constraints or alternative sources for packages with the uv add command. For example, to add a particular version of the Requests package:

BASH

$ uv add 'requests==2.31.0'

Or, to add a dependency sourced from GitHub (as opposed to the default PyPI):

BASH

$ uv add git+https://github.com/psf/requests

To remove a dependency, you can use uv remove:

BASH

$ uv remove requests

This will also remove any other packages which Requests depended on, provided other project dependencies do not need them.

Now we should be able to run our script.

BASH

$ uv run eva_data_analysis.py

Runtime and development dependencies

Tools like uv understand that there are two different types of dependencies: runtime dependencies and development dependencies. Runtime dependencies need to be installed for our code to run, like matplotlib for our code. Development dependencies are an essential part of the development process for a project, but are not required to run it. For example, mkdocs used to build the documentation for our software project or pytest to run tests.

With uv add matplotlib and uv add -r requirements.txt commands, uv will add all packages to the list of runtime dependencies in pyproject.toml (regardless if they are runtime or development dependencies - there is not way to tell the difference with requirements.txt).

To add mkdocs and pytest as development dependencies, the --group option can be used:

BASH

$ uv add --group dev mkdocs pytest

This will add a new section to the pyproject.toml file for development dependencies, e.g.

TOML

[dependency-groups]
dev = [
    "mkdocs>=1.6.1",
    "pytest>=9.1.1",
]

dev is treated as a special kind of group by uv. By default, uv will install all dev group dependencies alongside main package dependencies when you run uv commands. As a special group, the option --dev can be used instead of --group dev.

The --group option can be used to define other non-runtime dependency groups. For example, you might have an benchmark group which contains dependencies required to run benchmarks for your software.

Let’s run the tests for our project, replacing python with uv run:

BASH

$ uv run -m pytest tests/

When someone else installs our package on their machine using pip, only the runtime dependencies will be installed since development dependencies are not needed to run the code.

At this point, you can delete requirements.txt and carry on running your Python scripts or Python tools with uv. Recall that if you are using uv to run Python commands - you do not have to activate the environment explicitly. If you prefer to use Python directly, you will have to activate your environment first but switch to uv for managing it from whatever tools you used before.

Adding modules to a package


Python files within spacewalks are called submodules of the package. For example, a submodule called voskhod.py (named after the space mission where Alexei Leonov took the world’s first spacewalks) could be imported using the namespace spacewalks.voskhod.

Currently, our eva_data_analysis.py code is not a part of our spacewalks package. We can include our eva_data_analysis.py code as a module in our new spacewalks package. Move the file to the src/spacewalks directory give it a more concise name.

BASH

$ mv eva_data_analysis.py src/spacewalks/analyse.py

Now, we can import functions from the analysis code. Launch the Python console and import the read_json_to_dataframe function from the analyse module.

BASH

$ uv run python

In the Python console, run:

PYTHON

>>> from spacewalks.analyse import read_json_to_dataframe
>>> help(read_json_to_dataframe)
Help on function read_json_to_dataframe in module spacewalks.analyse:

read_json_to_dataframe(input_file)
    Read the data from a JSON file into a Pandas dataframe.
    Clean the data by removing any rows where the 'duration' value is missing.

    Args:
        input_file (file or str): The file object or path to the JSON file.

    Returns:
         eva_df (pd.DataFrame): The cleaned data as a dataframe structure

Python allows you to run installed modules as scripts with the -m option followed by the module namespace (e.g. spacewalks.analyse). Since uv run can be used in place of the python command, we can run the script with the following command:

BASH

$ uv run -m spacewalks.analyse

However, if we now try to run the tests:

BASH

$ uv run -m pytest tests/

They fail with the following output:

OUTPUT

================================================ ERRORS ================================================
_____________________________ ERROR collecting tests/test_eva_analysis.py ______________________________
ImportError while importing test module '***/spacewalks/tests/test_eva_analysis.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/opt/homebrew/Cellar/python@3.14/3.14.10/Frameworks/Python.framework/Versions/3.14/lib/python3.14/importlib/__init__.py:88: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
tests/test_eva_analysis.py:2: in <module>
    from eva_data_analysis import (
E   ModuleNotFoundError: No module named 'eva_data_analysis'
======================================= short test summary info ========================================
ERROR tests/test_eva_analysis.py
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
=========================================== 1 error in 0.10s ===========================================

This is because the module they were importing from has moved.

Challenge

Update tests

Go to tests/test_eva_analysis.py and update the import statements to import from our new analysis module. Confirm that the tests run after making your changes.

The top of tests/test_eva_analysis.py should now look like this:

PYTHON

import pytest
from spacewalks.analyse import (
    text_to_duration,
    calculate_crew_size
)

Building and distributing a package


uv build command can be used to build source distributions and binary distributions (wheels) for your project.

Once we have made sure our project is in the right structure, we can go ahead and build a distributable version of our software as before:

BASH

$ uv build
$ ls dist/
spacewalks-0.1.0-py3-none-any.whl
spacewalks-0.1.0.tar.gz

The one we care most about is the .whl or wheel file. This is the file that package managers use to distribute and install Python packages, so this is the file we would need to share with other people who want to install our software.

By convention distributable package names use hyphens, whereas module package names use underscores. While we could choose to use underscores in a distributable package name, we cannot use hyphens in a module package name, as Python will interpret them as a minus sign in our code when we try to import them.

Now if we gave this wheel file to someone else, they could install it using uv (or pip or another package installer).

BASH

$ python -m pip install spacewalks-0.1.0-py3-none-any.whl

And then they could import our package in their own Python environment:

PYTHON

import spacewalks

They can also run the spacewalks command:

BASH

$ spacewalks

Or the analysis module with:

BASH

$ python -m spacewalks.analyse
Callout

Managing the package version

After we have been working on our code for a while and want to publish an update, we just need to update the version number in the pyproject.toml file (using SemVer perhaps), then use uv to build and publish the new version.

uv can help easily increment the version number following Semantic Versioning conventions. For example, to increment the minor version number, we can do:

BASH

$ uv version --bump minor

Then the version number in pyproject.toml will be updated from 0.1.0 to 0.2.0.

Summary


uv provides a modern, standards-based workflow that simplifies Python project management by bringing dependency management, virtual environments, packaging and publishing together in a single tool.

Key Points

  • uv combines Python installation, dependency management, virtual environments, packaging and publishing into a single, high-performance tool.
  • pyproject.toml is the standard configuration file for modern Python projects and stores project metadata, dependencies and tool configuration.
  • Dependencies are declared in pyproject.toml, while uv.lock records the exact package versions needed to reproduce the project environment with uv.
  • uv automatically keeps the project environment and lock file synchronised, reducing manual environment management.
  • uv run executes commands in the correct project environment without requiring manual activation of a virtual environment.
  • Python packages are typically distributed as source distributions (.tar.gz) and wheels (.whl), which can be built using uv build.
  • Existing pip and venv development workflows can be migrated to uv with only a few commands for most projects.