Files and a command-line program
A function becomes a usable analysis tool when another person can supply data,
choose its options, and recognize a failed run. This lesson extends the
gene_tools package with a command that reads DNA sequences and writes their
lengths and GC fractions.
The command accepts an input TSV, an output path, and an optional minimum sequence length. It validates every record before it creates the output, even when the length filter would remove an invalid record. An existing output file causes an error, so another run cannot silently replace an earlier result.
Read functions, packages, and testing first. The documentation lesson explains the package layout and its API documentation.
Create the project
Section titled “Create the project”Create a directory named gene_tools_cli. Save each code block under the
filename in its first comment. Create the parent directories when needed.
The complete project
contains the same source, tests, and fixture generator.
[project]name = "gene-tools"version = "0.2.0"description = "Calculate validated DNA sequence summaries from a TSV."requires-python = ">=3.13,<3.14"dependencies = []
[project.scripts]gene-gc = "gene_tools.cli:main"
[dependency-groups]dev = ["pytest==9.2.0"]
[build-system]requires = ["uv_build==0.13.7"]build-backend = "uv_build"
[tool.pytest.ini_options]testpaths = ["tests"]The entry point maps gene-gc to a function. Its name is a command, while
gene_tools remains the importable Python package. The package initializer
exposes the calculation without executing the command.
"""Provide validated DNA sequence calculations."""
from gene_tools.sequence import calculate_gc_content
__all__ = ["calculate_gc_content"]Keep the calculation independent of files
Section titled “Keep the calculation independent of files”The calculation accepts a nonempty sequence containing A, C, G, and T. Lowercase letters are accepted. Ambiguous bases, gaps, and whitespace are rejected because removing them would change the denominator.
"""Calculate GC fractions for explicitly defined DNA alphabets."""
def calculate_gc_content(sequence: str) -> float: """Return the GC fraction of a nonempty DNA sequence.
Args: sequence: DNA bases A, C, G, and T, with lowercase letters accepted.
Returns: The fraction of characters that are G or C.
Raises: TypeError: If sequence is not a string. ValueError: If sequence is empty or contains an unsupported character. """ if not isinstance(sequence, str): raise TypeError("sequence must be a string") normalized = sequence.upper() if not normalized or not set(normalized) <= {"A", "C", "G", "T"}: raise ValueError("sequence must contain only A, C, G, and T") return (normalized.count("G") + normalized.count("C")) / len(normalized)Read, validate, and write through separate functions
Section titled “Read, validate, and write through separate functions”The TSV header must contain sequence_id followed by sequence. Identifiers
must be unique, nonempty, and free of surrounding whitespace. The reader
rejects missing or extra fields and reports the input record that failed.
The command stores the validated results in memory before it writes them. That choice makes complete validation explicit for this small example. A large-file implementation needs a separate policy for temporary output and errors discovered partway through a stream.
"""Read DNA sequences from TSV and write validated sequence summaries."""
import argparseimport csvfrom pathlib import Pathimport sys
from gene_tools.sequence import calculate_gc_content
def read_results(path: Path) -> list[tuple[str, int, float]]: """Read and validate every record before returning calculated results.
Args: path: UTF-8 TSV with sequence_id and sequence columns in that order.
Returns: Identifier, length, and GC fraction for each record in input order.
Raises: OSError: If the input cannot be opened or read. UnicodeError: If the file is not valid UTF-8. csv.Error: If quoted fields are malformed. ValueError: If the header, identifiers, or sequences are invalid. """ results = [] seen = set() with path.open(encoding="utf-8", newline="") as stream: reader = csv.DictReader(stream, delimiter="\t", strict=True) if reader.fieldnames != ["sequence_id", "sequence"]: raise ValueError("header must be sequence_id followed by sequence") for record_number, row in enumerate(reader, start=1): if None in row or any(value is None for value in row.values()): raise ValueError(f"record {record_number} must have two fields") identifier = row["sequence_id"] if not identifier or identifier != identifier.strip(): raise ValueError(f"record {record_number} has an invalid ID") if identifier in seen: raise ValueError(f"duplicate sequence_id: {identifier}") seen.add(identifier) sequence = row["sequence"] try: fraction = calculate_gc_content(sequence) except ValueError as error: raise ValueError(f"record {record_number}: {error}") from error results.append((identifier, len(sequence), fraction)) if not results: raise ValueError("input must contain at least one sequence") return results
def write_results(path: Path, results: list[tuple[str, int, float]]) -> None: """Create a summary TSV without replacing an existing destination.
Args: path: New UTF-8 TSV destination whose parent directory exists. results: Validated identifier, length, and fraction records.
Raises: FileExistsError: If the destination already exists. OSError: If the destination cannot be created or written. """ with path.open("x", encoding="utf-8", newline="") as stream: writer = csv.writer(stream, delimiter="\t", lineterminator="\n") writer.writerow(["sequence_id", "length", "gc_fraction"]) for identifier, length, fraction in results: writer.writerow([identifier, length, f"{fraction:.6f}"])
def build_parser() -> argparse.ArgumentParser: """Return the parser for the sequence-summary command.
Returns: A parser with required file paths and a minimum-length option. """ parser = argparse.ArgumentParser( description="Read sequence_id/sequence TSV and write GC fractions." ) parser.add_argument("--input", type=Path, required=True, help="UTF-8 input TSV with unique sequence IDs") parser.add_argument("--output", type=Path, required=True, help="new summary TSV; existing files are refused") parser.add_argument("--min-length", type=int, default=1, help="minimum sequence length to retain; default 1") return parser
def main(argv: list[str] | None = None) -> int: """Execute the command and report expected input or file failures.
Args: argv: Explicit arguments, or None to use the process arguments.
Returns: Zero on success or two for an expected input or file error.
Raises: SystemExit: If argparse handles help or rejects the command syntax. """ parser = build_parser() arguments = parser.parse_args(argv) try: if arguments.min_length < 1: raise ValueError("min-length must be positive") if arguments.input.resolve() == arguments.output.resolve(): raise ValueError("input and output paths must differ") results = read_results(arguments.input) selected = [row for row in results if row[1] >= arguments.min_length] write_results(arguments.output, selected) except (OSError, UnicodeError, csv.Error, ValueError) as error: print(f"error: {error}", file=sys.stderr) return 2 print(f"Wrote {len(selected)} of {len(results)} sequences.") return 0
if __name__ == "__main__": raise SystemExit(main())with closes the file when its block ends, including after an exception.
The x mode requires a new output file. argparse converts paths and integer
options, but the explicit validation still rejects a nonpositive minimum.
The main guard runs the command when Python executes this module directly.
An import defines its functions without reading files or parsing the importing
program’s arguments. The installed entry point calls the same main function.
Create invented input and run the command
Section titled “Create invented input and run the command”The fixture generator refuses to replace an existing input file. Run it once in the new project directory. Each record describes an invented DNA sequence.
"""Create the invented DNA input without replacing an existing file."""
from pathlib import Path
with Path("sequences.tsv").open("x", encoding="utf-8", newline="") as stream: stream.write("sequence_id\tsequence\n") stream.write("seq_a\tACGT\nseq_b\tGGAACC\nseq_c\tatat\n")uv syncuv run python make_fixture.pyuv run gene-gc --input sequences.tsv --output summaries.tsvcat summaries.tsvuv run python -m gene_tools.cli --input sequences.tsv --output long_sequences.tsv --min-length 5cat long_sequences.tsvWrote 3 of 3 sequences.sequence_id length gc_fractionseq_a 4 0.500000seq_b 6 0.666667seq_c 4 0.000000Wrote 1 of 3 sequences.sequence_id length gc_fractionseq_b 6 0.666667Both command forms execute the same program. Output fractions use six decimal places, while the calculation retains Python floating-point values internally. A filter that retains no records still writes a header-only TSV and reports that selection explicitly.
Test the command through its external behavior
Section titled “Test the command through its external behavior”Each test receives its own directory through tmp_path. The tests invoke a
separate Python process, so they check the module entry point, exit status,
and output files together. The pure calculation also has known-answer checks.
"""Verify sequence calculations and the command's external contract."""
from pathlib import Pathimport subprocessimport sys
import pytest
from gene_tools import calculate_gc_content
def run_cli(directory: Path, *extra: str) -> subprocess.CompletedProcess[str]: """Execute the module against conventional files in a test directory.
Args: directory: Independent directory for the test input and output. *extra: Additional command arguments.
Returns: The completed process with captured standard output and error. """ return subprocess.run( [sys.executable, "-m", "gene_tools.cli", "--input", "input.tsv", "--output", "output.tsv", *extra], cwd=directory, capture_output=True, text=True, check=False, )
@pytest.mark.parametrize( ("sequence", "expected"), [("ATAT", 0.0), ("GCGC", 1.0), ("acgt", 0.5)],)def test_gc_fraction(sequence: str, expected: float) -> None: """Check a fraction against its direct base count.
Args: sequence: Valid sequence with a known composition. expected: Independently specified GC fraction. """ assert calculate_gc_content(sequence) == pytest.approx(expected)
def test_success_and_filter(tmp_path: Path) -> None: """Check order, fraction units, and selection through the command.
Args: tmp_path: Independent pytest directory. """ source = "sequence_id\tsequence\nshort\tAT\nlong\tGCGC\n" (tmp_path / "input.tsv").write_text(source, encoding="utf-8") result = run_cli(tmp_path, "--min-length", "3") assert result.returncode == 0 assert result.stderr == "" assert result.stdout == "Wrote 1 of 2 sequences.\n" assert (tmp_path / "output.tsv").read_text() == ( "sequence_id\tlength\tgc_fraction\nlong\t4\t1.000000\n" ) assert (tmp_path / "input.tsv").read_text() == source
@pytest.mark.parametrize("body", [ "", "sequence_id\tsequence\n", "id\tsequence\na\tACGT\n", "sequence_id\tsequence\na\tACGT\na\tTT\n", "sequence_id\tsequence\n\tACGT\n", "sequence_id\tsequence\n a\tACGT\n", "sequence_id\tsequence\na\t\n", "sequence_id\tsequence\na\tACGN\n", "sequence_id\tsequence\na\n", "sequence_id\tsequence\na\tACGT\textra\n", "sequence_id\tsequence\ngood\tACGT\nbad\tN\n",])def test_invalid_input_creates_no_output(tmp_path: Path, body: str) -> None: """Reject all invalid records before creating an output file.
Args: tmp_path: Independent pytest directory. body: Input containing a schema or record defect. """ (tmp_path / "input.tsv").write_text(body, encoding="utf-8") result = run_cli(tmp_path, "--min-length", "20") assert result.returncode == 2 assert result.stderr.startswith("error: ") assert not (tmp_path / "output.tsv").exists()
def test_existing_output_is_preserved(tmp_path: Path) -> None: """Refuse to replace an earlier result.
Args: tmp_path: Independent pytest directory. """ (tmp_path / "input.tsv").write_text("sequence_id\tsequence\na\tACGT\n") (tmp_path / "output.tsv").write_text("earlier result\n") assert run_cli(tmp_path).returncode == 2 assert (tmp_path / "output.tsv").read_text() == "earlier result\n"
def test_missing_input(tmp_path: Path) -> None: """Return a file error without creating an output.
Args: tmp_path: Independent pytest directory. """ assert run_cli(tmp_path).returncode == 2 assert not (tmp_path / "output.tsv").exists()
def test_invalid_option(tmp_path: Path) -> None: """Reject a nonpositive minimum before file creation.
Args: tmp_path: Independent pytest directory. """ result = run_cli(tmp_path, "--min-length", "0") assert result.returncode == 2 assert "min-length must be positive" in result.stderr assert not (tmp_path / "output.tsv").exists()
def test_empty_selection(tmp_path: Path) -> None: """Write a header when every valid record is below the length threshold.
Args: tmp_path: Independent pytest directory. """ (tmp_path / "input.tsv").write_text("sequence_id\tsequence\na\tACGT\n") result = run_cli(tmp_path, "--min-length", "10") assert result.returncode == 0 assert result.stdout == "Wrote 0 of 1 sequences.\n" assert (tmp_path / "output.tsv").read_text() == ( "sequence_id\tlength\tgc_fraction\n" )
def test_same_input_and_output(tmp_path: Path) -> None: """Refuse to use the input path as the output path.
Args: tmp_path: Independent pytest directory. """ source = "sequence_id\tsequence\na\tACGT\n" (tmp_path / "input.tsv").write_text(source) result = run_cli(tmp_path, "--output", "input.tsv") assert result.returncode == 2 assert "paths must differ" in result.stderr assert (tmp_path / "input.tsv").read_text() == source
def test_import_has_no_command_effect(tmp_path: Path) -> None: """Import the CLI without running argument parsing or creating files.
Args: tmp_path: Independent pytest directory. """ probe = tmp_path / "import_probe.py" probe.write_text("import gene_tools.cli\nprint('import succeeded')\n") result = subprocess.run( [sys.executable, str(probe)], cwd=tmp_path, capture_output=True, text=True, check=False, ) assert result.returncode == 0 assert result.stdout == "import succeeded\n" assert result.stderr == "" created_names = sorted(path.name for path in tmp_path.iterdir()) assert created_names == ["import_probe.py"]uv run pytest -qq --tb=short --color=no -p no:cacheprovider..................... [100%]The invalid-input tests apply a length filter that would remove every record. They still require an error because a filter must not conceal invalid source data. The import test detects a missing main guard, and the output tests detect an accidental replacement of an existing result.
Practice with a new option
Section titled “Practice with a new option”Add a maximum sequence length and define what happens when it is smaller than the minimum. Write the input contract and tests before changing the command. Keep complete input validation before selection, and preserve the output-file protection. Explain whether the new option changes the calculation or only the selection of records.
Further reading
Section titled “Further reading”The Python file tutorial
explains file modes, encodings, and with. The
csv reference
explains dictionary readers and the newline argument used for TSV files.
The argparse reference defines option conversion, required arguments, and help. The main-module guide explains why an import and direct execution take different paths.
The uv entry-point guide connects a project command to a Python function. The pytest temporary-directory guide explains the independent directories used by the file tests.