Skip to content

Create a Python Package

A Python package gives another project an importable function and a defined set of dependencies. An import from your source directory can find a local file that never reaches the distribution.

This lesson builds gene-tools, a small package that calculates the GC fraction of a DNA sequence. It uses the function from Documentation and style and adds the complete path from source files to an installed wheel. The complete project download contains the files below and a dependency lockfile.

Separate the project, import, and distribution

Section titled “Separate the project, import, and distribution”
Name Meaning in this example
gene_tools_package/ This directory holds the development project.
gene-tools This is the distribution name in the project metadata.
gene_tools This is the name that Python imports.
src/gene_tools/sequence.py This module implements the public function.
dist/ This directory receives the wheel and source archive.

The src layout keeps the import package below the project root. Install the project into its environment before running tests. This catches an omitted package installation instead of relying on the current directory.

Create gene_tools_package/ and save each file under its displayed path. Create the parent directories as needed. Run the shell commands from that project directory in Bash. Use Python 3.13 and uv, as described in Working with packages.

gene_tools_package/
pyproject.toml
README.md
src/gene_tools/__init__.py
src/gene_tools/sequence.py
tests/test_sequence.py
docs/source/conf.py
docs/source/index.rst
scripts/check_install.py
pyproject.toml
[project]
name = "gene-tools"
version = "0.1.0"
description = "Calculate a GC fraction for a DNA sequence."
readme = "README.md"
requires-python = ">=3.13,<3.14"
dependencies = []
[dependency-groups]
dev = ["pytest==9.2.0", "sphinx==9.2.0"]
[build-system]
requires = ["uv_build==0.13.7"]
build-backend = "uv_build"
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "--import-mode=importlib"

[project] describes the distribution and its runtime requirements. This function uses only the standard library, so dependencies is empty. The development group supplies tests and documentation tools. Installing the wheel into another project does not install that group.

[build-system] selects the program that creates the distribution. The uv_build backend maps the distribution name gene-tools to src/gene_tools. Its version is separate from the package version. The Python range describes the interpreter used here; broaden it only after testing the additional interpreter versions.

Save this short description as README.md.

# gene-tools
The package calculates the GC fraction of one DNA sequence.
It accepts uppercase or lowercase A, C, G, and T.
It rejects empty input, whitespace, gaps, and ambiguous bases.
The result is a fraction between zero and one.
Run `uv sync --locked` to restore the development environment.
Run `uv run pytest` to execute the unit tests.

The README describes what an installer receives. Before distributing your own project, add its authorship and license information and choose a distribution name that identifies your project. The example does not reserve gene-tools on a public registry.

Implement and document the public function

Section titled “Implement and document the public function”
src/gene_tools/sequence.py
"""Calculate summary values for DNA sequences."""
def calculate_gc_content(sequence: str) -> float:
"""Calculate the GC fraction of a DNA sequence.
Args:
sequence: A nonempty DNA sequence containing A, C, G, and T.
Lowercase letters are accepted. Whitespace is not removed.
Returns:
The fraction of bases that are G or C, between zero and one.
Raises:
TypeError: If sequence is not a string.
ValueError: If the sequence is empty or contains another character.
"""
if not isinstance(sequence, str):
raise TypeError("sequence must be a string")
normalized_sequence = sequence.upper()
valid_bases = {"A", "C", "G", "T"}
if not normalized_sequence or not set(normalized_sequence) <= valid_bases:
raise ValueError("sequence must contain only A, C, G, and T")
gc_count = normalized_sequence.count("G") + normalized_sequence.count("C")
return gc_count / len(normalized_sequence)

Args, Returns, and Raises document behavior that the return type alone cannot express. In particular, N is rejected rather than removed from the denominator. A percentage would require a different return contract.

The initializer exposes the function at the package root.

src/gene_tools/__init__.py
"""Provide DNA sequence utilities."""
from gene_tools.sequence import calculate_gc_content
__all__ = ["calculate_gc_content"]

Callers can use from gene_tools import calculate_gc_content without knowing which module implements it. __all__ declares the names used by wildcard imports; it does not prevent access to other module attributes. Keep analyses and file writes out of import code because tests and documentation tools import the package too.

tests/test_sequence.py
import pytest
from gene_tools import calculate_gc_content
@pytest.mark.parametrize(
("sequence", "expected"),
[("A", 0.0), ("G", 1.0), ("ATAT", 0.0), ("GCGC", 1.0),
("ACGT", 0.5), ("acgt", 0.5)],
)
def test_known_gc_fraction(sequence, expected) -> None:
"""Check a sequence against its expected fraction.
Args:
sequence: DNA input for the known case.
expected: Independently specified GC fraction.
"""
assert calculate_gc_content(sequence) == pytest.approx(expected)
@pytest.mark.parametrize(
"sequence", ["", "AUGC", "ACGN", "AC GT", "ACGT\n", "A-C"]
)
def test_rejects_invalid_sequence(sequence) -> None:
"""Check rejection of an invalid string.
Args:
sequence: Empty input or a string containing unsupported characters.
"""
with pytest.raises(ValueError, match="only A, C, G, and T"):
calculate_gc_content(sequence)
@pytest.mark.parametrize("sequence", [None, 42, b"ACGT", ["A", "C"]])
def test_rejects_non_string(sequence) -> None:
"""Check rejection of an input with the wrong type.
Args:
sequence: An object that is not a string.
"""
with pytest.raises(TypeError, match="must be a string"):
calculate_gc_content(sequence)
def test_repetition_preserves_fraction() -> None:
"""Check that repeating a sequence preserves its fraction."""
sequence = "AACGT"
assert calculate_gc_content(sequence * 7) == pytest.approx(
calculate_gc_content(sequence)
)

These tests import the public name. They can detect a missing export as well as an incorrect denominator. The repetition test checks a property of the calculation, while the small known answers establish its scale. The testing lesson explains numerical tolerances and additional boundary cases.

Create the environment and run the tests.

Terminal window
uv sync
uv run --locked pytest -qq --tb=short --color=no -p no:cacheprovider
................. [100%]

Commit pyproject.toml and the generated uv.lock. A collaborator restores the recorded dependencies with uv sync --locked. Keep .venv, dist, and generated documentation out of Git. Add a future runtime dependency with uv add package_name; use uv add --dev package_name for a development tool. The lockfile fixes this development environment. It does not constrain every environment that installs the wheel.

Sphinx imports the installed package. Its Napoleon extension reads the Google docstring sections, and autodoc turns the public function into an API entry.

docs/source/conf.py
"""Configure the package API documentation."""
project = "gene-tools"
extensions = ["sphinx.ext.autodoc", "sphinx.ext.napoleon"]
autodoc_typehints = "description"
root_doc = "index"
html_theme = "alabaster"
exclude_patterns = []
.. file: docs/source/index.rst
gene-tools
==========
The package calculates the GC fraction of one DNA sequence.
.. autofunction:: gene_tools.calculate_gc_content

Build the HTML with warnings treated as errors.

Terminal window
uv run --locked sphinx-build -q -E -a -W -N -b html docs/source docs/build/html

Open docs/build/html/index.html. Check that its input description, result, and exceptions agree with the tests. The documentation lesson extends this setup to an automatically generated module reference.

Terminal window
uv build

The wheel in dist/gene_tools-0.1.0-py3-none-any.whl is the installable distribution. The source archive in dist/gene_tools-0.1.0.tar.gz contains the material used to build it. By default, uv build builds the source archive first and then builds the wheel from that archive. A missing source file can therefore break this step even when local tests pass.

The py3-none-any tag fits this pure Python package. A package with compiled extensions can require wheels for particular interpreters and platforms. The build command saves both files locally.

Test the installed wheel in another project

Section titled “Test the installed wheel in another project”

Save this script in scripts/check_install.py. It checks both the result and the origin of the imported module.

scripts/check_install.py
"""Check the installed distribution outside its source project."""
from importlib.metadata import version
from pathlib import Path
import sysconfig
import gene_tools
package_path = Path(gene_tools.__file__).resolve()
installed_library = Path(sysconfig.get_path("purelib")).resolve()
assert package_path.is_relative_to(installed_library)
assert version("gene-tools") == "0.1.0"
assert gene_tools.calculate_gc_content("ACGT") == 0.5
print(f"Installed version: {version('gene-tools')}")
print(f"GC fraction: {gene_tools.calculate_gc_content('ACGT')}")

Create a separate consumer project. The commands use a fresh directory and install the wheel file, rather than a path to the package source.

Terminal window
mkdir consumer
cd consumer
uv init --bare --name package-consumer --python 3.13 --no-workspace
uv add ../dist/gene_tools-0.1.0-py3-none-any.whl
cp ../scripts/check_install.py check_install.py
uv run --locked python check_install.py
Installed version: 0.1.0
GC fraction: 0.5

The consumer has its own .venv. Copying the script here also removes the source project’s script directory from Python’s import search path. The path assertion fails if the import comes from an editable source checkout.

Run the same unit tests against that installed wheel. These commands continue inside consumer/.

Terminal window
uv add --dev pytest==9.2.0
cp -r ../tests tests
uv run --locked pytest -qq --import-mode=importlib --tb=short --color=no \
-p no:cacheprovider tests
................. [100%]

An editable development install follows changes under src/. An installed wheel keeps the code that was built. After a source change, rebuild the wheel and repeat this check in a fresh consumer directory.

Keep reusable calculations inside the import package. Keep notebooks, private data, credentials, and generated analyses outside the distribution. If the package needs a terminal command, the command-line lesson adds an entry point and tests its arguments and file behavior.

Change the package version when you prepare another distribution. Review changes to accepted input, returned values, and public imports because callers depend on those contracts. Sharing the wheel or source archive is a separate action from building it locally; a public index also needs a suitable name, complete metadata, and credentials.

The Python Packaging User Guide explains project metadata, source distributions, and wheels. Use it when you add license files or prepare a project for a public index.

The uv build backend guide defines package discovery and file inclusion. It explains why gene-tools maps to src/gene_tools and how to include package data.

The uv distribution guide describes the source archive and wheel build sequence. It helps diagnose a distribution that omits a file available in the checkout.

The pytest integration guide explains the src layout and import modes. These choices help ensure that a test imports the package you intended to install.

The Sphinx Napoleon reference describes Google docstring support. It connects the function’s input and error contract to the generated API page.