Documentation and Style
A docstring explains the contract that a type annotation cannot express. For a GC calculation, that contract includes the accepted alphabet, the treatment of lowercase letters, and whether the result is a fraction or a percentage.
This lesson creates an installable package. pytest imports its code, and Sphinx imports the same code to build the API reference.
The Create a package lesson adds distribution files and a separate consumer project. It tests the built wheel after installation outside the source directory.
Create a package
Section titled “Create a package”Create a directory named gene_tools. Save each block under the filename in its first comment. Create the parent directories when needed.
[project]name = "gene-tools"version = "0.1.0"description = "A small DNA sequence utility."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"]The build backend finds src/gene_tools from the project name. The package initializer establishes a public import path.
"""Provide DNA sequence utilities."""
from gene_tools.sequence import calculate_gc_content
__all__ = ["calculate_gc_content"]Document behavior and errors
Section titled “Document behavior and errors”Use snake_case for functions and variables. Use CapWords for classes and four spaces for indentation. Public functions have type annotations and Google style docstrings with the sections that apply to their behavior.
"""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)This function rejects N, gaps, and spaces. Removing those characters would change the denominator, so a function that permits them needs a different contract.
The return annotation says that the function returns a float. The docstring supplies the units and the input restrictions. Type annotations do not perform runtime checks; the explicit checks raise the documented errors.
Test the public behavior
Section titled “Test the public behavior”Save the tests below in tests/test_sequence.py. Each known answer follows from the sequence itself. The tests use the public import path to check the package initializer as well as the function.
import pytest
from gene_tools import calculate_gc_content
@pytest.mark.parametrize( ("sequence", "expected"), [("ATAT", 0.0), ("GCGC", 1.0), ("ACGT", 0.5), ("acgt", 0.5)],)def test_calculate_gc_content_known_answer(sequence, expected) -> None: assert calculate_gc_content(sequence) == pytest.approx(expected)
@pytest.mark.parametrize("sequence", ["", "AUGC", "ACGN", "AC GT", "ACGT\n"])def test_calculate_gc_content_rejects_invalid_bases(sequence) -> None: with pytest.raises(ValueError, match="only A, C, G, and T"): calculate_gc_content(sequence)
def test_calculate_gc_content_rejects_non_string() -> None: with pytest.raises(TypeError, match="must be a string"): calculate_gc_content(None)After you save the files above, run uv sync in the project directory. uv installs the package into the project environment, so tests and Sphinx can import it without a sys.path modification.
Run the tests from the project directory. The quiet flags remove the elapsed time from the displayed output.
uv run pytest -qq --tb=short --color=no -p no:cacheprovider.......... [100%]Short test functions can use descriptive test_* names without docstrings. The testing lesson adds numerical tolerances, invariants, invalid-input tests, and reproducible random input.
Configure Sphinx
Section titled “Configure Sphinx”Keep the configuration and the root document in the same source directory. autodoc imports the package and reads its docstrings. napoleon converts Google docstring sections into Sphinx markup.
"""Configure the gene_tools API documentation."""
project = "gene_tools"extensions = ["sphinx.ext.autodoc", "sphinx.ext.napoleon"]autodoc_typehints = "description"root_doc = "index"html_theme = "alabaster"exclude_patterns = []The root document includes the API pages that sphinx-apidoc generates. Save this reStructuredText file before the build.
.. file: docs/source/index.rst
gene_tools==========
The package calculates the GC fraction of DNA sequences.
.. toctree:: :maxdepth: 2
api/modulesGenerate the API pages, then build the HTML. -E -a rebuilds every document, and -W treats warnings as errors. -q suppresses progress messages, and -N disables terminal colors.
uv run sphinx-apidoc -f -o docs/source/api src/gene_toolsuv run sphinx-build -q -E -a -W --keep-going -N -b html docs/source docs/build/htmlprintf '%s\n' 'Documentation build completed.'Documentation build completed.Open docs/build/html/index.html in a browser. The generated API page includes the function signature, accepted input, return units, and documented exceptions. Sphinx imports modules during this build, so keep file writes and analyses out of module-level import code.
Review the contract
Section titled “Review the contract”Before a merge, compare the implementation, its tests, and its docstring.
| Check | Required action |
|---|---|
| Names | Use snake_case for functions and CapWords for classes. |
| Types | Annotate public parameters and return values. |
| Meaning | State units, accepted input, and error conditions. |
| Tests | Check known answers and rejected inputs. |
| API reference | Build Sphinx with warnings treated as errors. |
The command-line lesson extends this package with a gene-gc command, TSV input, and file validation.
It keeps the public calculation importable while the command handles paths, arguments, and error messages.
Further reading
Section titled “Further reading”- The Google Python Style Guide defines function docstrings and their sections. Use it to keep the contract next to the implementation.
- The uv build backend documentation explains the
srclayout and package discovery. It also explains when to configure a different module name. - The Sphinx autodoc reference describes module imports and generated API entries. Its import requirements explain why this example installs the package first.
- The Sphinx Napoleon reference lists supported Google docstring sections. It helps identify markup that Sphinx does not interpret as intended.
- The sphinx-build reference describes rebuild options and warnings. These options make a documentation failure visible to a test workflow.