Working with Packages
Python’s standard library provides modules for paths, mathematics, and text. Third-party packages add analysis tools. PyPI distributes many of those packages.
Use Python 3.13 for this lesson. Complete the project setup
before running the examples that import NumPy. Save the Python fences in page
order as script.py inside that project.
Importing packages
Section titled “Importing packages”Before using a package, you need to import it. Python offers several ways to do this.
import
Section titled “import”The simplest approach imports the entire module.
import math
print(math.sqrt(81))9.0You then access functions and classes using the module name as a prefix.
from … import
Section titled “from … import”You can import specific items from a module. This lets you use them directly without the module prefix.
from pathlib import Path
p = Path("sample_data.fastq.gz")print(p.stem)print(p.suffix)print(p.name)sample_data.fastq.gzsample_data.fastq.gzPath is very useful for working with file paths in bioinformatics pipelines. It handles path separators across operating systems automatically.
Aliases
Section titled “Aliases”Some packages have long names. The community has adopted standard short aliases for common packages. Use the as keyword to create an alias.
import numpy as np
counts = np.array([100, 250, 50, 300, 75])print(counts)print(counts.mean())print(counts.std())[100 250 50 300 75]155.0100.4987562112089You will see np for NumPy, pd for pandas, and plt for matplotlib in nearly every tutorial and codebase. Stick with these conventions so your code is readable to others.
Standard library highlights
Section titled “Standard library highlights”The standard library includes many useful modules. Here are a few that come up often in bioinformatics work.
| Module | Purpose |
|---|---|
os |
Interact with the operating system, environment variables |
pathlib |
Object-oriented file path handling |
csv |
Read and write CSV/TSV files |
collections |
Specialized container types like Counter and defaultdict |
gzip |
Read and write gzip-compressed files |
json |
Parse and write JSON data |
sys |
Access command-line arguments and system info |
collections.Counter
Section titled “collections.Counter”Counter tallies how often each item appears in a list. This is handy for counting gene occurrences, k-mers, or any repeated elements.
from collections import Counter
gene_list = ["TP53", "BRCA1", "TP53", "EGFR", "BRCA1", "TP53"]gene_counts = Counter(gene_list)print(gene_counts)print(gene_counts.most_common(2))Counter({'TP53': 3, 'BRCA1': 2, 'EGFR': 1})[('TP53', 3), ('BRCA1', 2)]csv module
Section titled “csv module”Many bioinformatics tools produce tab-separated output files. The csv module handles both CSV and TSV formats.
import csvimport io
tsv_data = ("gene\tlog2fc\tpvalue\n" "TP53\t2.5\t0.001\n" "BRCA1\t-1.8\t0.003\n" "EGFR\t3.2\t0.0001")reader = csv.DictReader(io.StringIO(tsv_data), delimiter="\t")for row in reader: print(f"{row['gene']}: log2fc={row['log2fc']}, p={row['pvalue']}")TP53: log2fc=2.5, p=0.001BRCA1: log2fc=-1.8, p=0.003EGFR: log2fc=3.2, p=0.0001DictReader maps each row to a dictionary using the header as keys. This makes your code more readable than indexing by column number.
Installing packages with uv
Section titled “Installing packages with uv”These guides use uv to manage each project’s dependencies and environment.
If uv is not available in your terminal, follow its
installation guide
before continuing. Run the shell commands below in a terminal, not at Python’s
>>> prompt.
Setting up a new project
Section titled “Setting up a new project”First, create a project directory and initialize it with uv.
mkdir gene_analysiscd gene_analysisuv init --bare --python 3.13uv init --bare creates pyproject.toml without an example application or
package build configuration. It does not
create .venv by itself. A command that synchronizes the project, such as
uv add, uv sync, or uv run, creates the environment when needed.
Adding packages
Section titled “Adding packages”Use uv add to install packages. This updates your pyproject.toml automatically.
uv add pandas==3.1.1 numpy==2.5.4You can add multiple packages at once. These versions reproduce this lesson.
pyproject.toml records their requirements, while uv.lock records their
resolved dependencies. Other projects can choose different versions.
Running scripts
Section titled “Running scripts”Save your Python code in script.py inside the project directory. Use uv run
from that directory to execute the saved file in the project environment.
uv run python script.pyThis ensures Python uses the packages installed in your project’s virtual environment.
pyproject.toml
Section titled “pyproject.toml”After running uv init and adding some packages, your pyproject.toml will look something like this:
[project]name = "gene-analysis"version = "0.1.0"requires-python = ">=3.13"dependencies = [ "numpy==2.5.4", "pandas==3.1.1",]An exact requirement such as numpy==2.5.4 selects that release. A requirement
such as numpy>=2.5.4 permits later releases too. The accompanying uv.lock
records the full resolution, including indirect dependencies. Keep both files in
Git, along with .python-version when the project supplies it. Keep .venv
out of Git because each machine creates its own environment. See the
uv project guide.
Restore a shared project
Section titled “Restore a shared project”After you clone a project, enter its directory before you restore its
dependencies. The directory must contain its committed pyproject.toml and
uv.lock, together with the scripts and any required input files.
uv sync --lockeduv run --locked python script.pyReplace script.py with that project’s documented entry script. --locked
requires the lockfile to agree with the project requirements and stops if it
would need an update. It does not silently choose new package versions. The
uv synchronization guide
explains how this differs from --frozen, which skips that agreement check.
The lockfile does not contain your data, external programs, or system libraries. Record those requirements in the project README or provide the required container. Run the project’s checks after restoration before you compare analysis results.
Key bioinformatics packages
Section titled “Key bioinformatics packages”These are the most commonly used third-party packages in bioinformatics and data science.
| Package | Purpose | Install command |
|---|---|---|
| pandas | Tabular data manipulation | uv add pandas |
| polars | Fast DataFrame library for large datasets | uv add polars |
| numpy | Numerical arrays and math operations | uv add numpy |
| scipy | Statistical tests and scientific computing | uv add scipy |
| scikit-learn | Machine learning algorithms | uv add scikit-learn |
| scanpy | Single-cell RNA-seq analysis | uv add scanpy |
| pysam | Read and write BAM/SAM/VCF files | uv add pysam |
| biopython | Sequence analysis, BLAST parsing, file I/O | uv add biopython |
| matplotlib | General-purpose plotting | uv add matplotlib |
| seaborn | Statistical data visualization | uv add seaborn |
You do not need all of these at once. Add packages as your project requires them.
Virtual environments
Section titled “Virtual environments”A virtual environment is an isolated Python installation for a single project. It prevents packages from one project from interfering with another.
When uv first synchronizes the project, it creates .venv inside the project
directory. That environment contains the Python executable and installed
packages used by the project.
You do not need to activate the virtual environment manually. Running
uv run python script.py selects it. In a Bash terminal on Linux or macOS,
you can activate it for interactive use with this command:
source .venv/bin/activateEach project should have its own virtual environment. Never install packages into your system Python.
Quick reference
Section titled “Quick reference”| Task | Command |
|---|---|
| Create a new project | uv init |
| Add a package | uv add <package> |
| Add multiple packages | uv add pandas numpy scipy |
| Remove a package | uv remove <package> |
| Run a script | uv run python script.py |
| Restore the committed dependency resolution | uv sync --locked |
| Import a module | import module_name |
| Import a specific item | from module import item |
| Import with alias | import numpy as np |
Build a command from a package
Section titled “Build a command from a package”The Create a package lesson builds a complete package with documentation and unit tests. It creates a wheel and source archive, then tests the installed wheel in a separate project.
The command-line project adds an installed entry point to gene_tools.
It connects a pyproject.toml command name to main, then tests file input, validation, and output in temporary directories.
Use that lesson after the package setup here when a script needs explicit options and predictable failure behavior.
Next steps
Section titled “Next steps”Now that you know how to install and import packages, you are ready to work with tabular data. Head to Pandas Essentials to learn how to load, filter, and analyze data with pandas.
Further reading
Section titled “Further reading”The Python tutorial explains imports and packages. See Python tutorial: Modules.
The uv guide explains project dependencies and lockfiles. See Working on projects with uv.