Registry / data / pyfaidx

pyfaidx

JSON →
library0.9.0.4pypypi✓ verified 25d ago

pyfaidx is a Python library that provides efficient, pythonic random access to subsequences within FASTA files, compatible with samtools index format (.fai). It allows for fast retrieval and in-place modification without loading the entire file into memory. The current version is 0.9.0.4, with frequent minor updates and bug fixes.

pip install pyfaidx
INSTALL
IMPORT
SIG · PYFAIDX
P
pyfaidx
datapythonv0.9.0.4
Install
1.7s avg
Import
107ms
Disk
17MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.9.0.4 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.112s · 18.9MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 1.7s · import 0.102s · 19MB
17MB installed
● package 17MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Fasta
from pyfaidx import Fasta

This quickstart demonstrates how to initialize a `Fasta` object, access sequences by their header names, retrieve subsequences using slicing, and perform operations like reverse complementation. It also highlights the default 1-based indexing for sequence attributes, while slicing remains 0-based Pythonic.

import os from pyfaidx import Fasta # Create a dummy FASTA file for demonstration fasta_content = ( ">chr1 description of chromosome 1\n" "ATGCGTACGTACGTACGTAGCTAGCTAGCTACGTAGCTACGTAGCTAGCTACGTACGT\n" "CGTAGCTACGTAGCTACGTAGCTACGTAGCTAGCTACGTAGCTACGTACGTAGCTACG\n" ">chr2 description of chromosome 2\n" "GATTACAGATTACAGATTACAGATTACAGATTACAGATTACAGATTACAGATTACAGA\n" "TTACAGATTACAGATTACAGATTACAGATTACAGATTACAGATTACAGATTACAGATT\n" ) file_path = "example.fasta" with open(file_path, "w") as f: f.write(fasta_content) # Open the FASTA file, an index (.fai) will be created if it doesn't exist genes = Fasta(file_path) # Access a sequence by its header name (case-sensitive) chr1_sequence = genes['chr1'] print(f"Chromosome 1 full length: {len(chr1_sequence)}") print(f"First 10 bases of chr1: {chr1_sequence[:10]}") # Pythonic 0-based slicing # Retrieve a subsequence using 1-based coordinates (like samtools faidx) # pyfaidx object slicing is 0-based, but Sequence object attributes are 1-based. # To get 1-based subsequence string, you'd typically use the string slice directly from the FastaRecord. # The example below shows how to get a 1-based range (e.g. for printing a 1-based output) # Note: Slicing `genes['chr1'][start_0_based:end_0_based]` # For 1-based '21-30', it means Python slice `[20:30]` sub_sequence_1_based = genes['chr1'][20:30] # This gets bases 21-30 (1-based) print(f"chr1 1-based coord 21-30: {sub_sequence_1_based.seq}") print(f" .start (1-based): {sub_sequence_1_based.start}") print(f" .end (1-based): {sub_sequence_1_based.end}") # Get the reverse complement of a sequence rc_sequence = genes['chr2'][::-1].complement print(f"Reverse complement of chr2 start: {rc_sequence.seq[:20]}") # Clean up the dummy file and its index os.remove(file_path) os.remove(file_path + ".fai")
faidx --version
Debug
Known issues
breakingA bug in the new BGZF indexing strategy introduced in v0.9.0 affected versions up to v0.9.0.2. Users of pyfaidx v0.9.0, v0.9.0.1, or v0.9.0.2 should upgrade to v0.9.0.3 or later to avoid potential indexing issues with BGZF compressed FASTA files.
fix
Upgrade to pyfaidx version 0.9.0.3 or higher (`pip install --upgrade pyfaidx`).
affects: 0.9.0 - 0.9.0.2
gotchapyfaidx uses 1-based (closed) coordinates for sequence attributes like `.start` and `.end` on `Sequence` objects, mirroring samtools faidx. However, Python's native slicing (`sequence[start:end]`) remains 0-based and half-open. This can be a common source of off-by-one errors if not carefully managed. You can initialize `Fasta(..., one_based_attributes=False)` to change the `.start/.end` attributes, but it won't affect slicing behavior.
fix
Be mindful of the coordinate system. For Pythonic 0-based slicing, use `fasta_obj['name'][0_based_start:0_based_end]`. If you need to work with 1-based coordinates for display or interoperability with tools like samtools, remember to adjust your slice indices accordingly (e.g., 1-based `start` corresponds to 0-based `start - 1`).
affects: All versions
gotchaFASTA files require consistent line lengths (apart from the last line of a sequence) for pyfaidx to correctly build an index and retrieve subsequences. Inconsistent line lengths can lead to errors during indexing or incorrect sequence retrieval.
fix
Ensure your FASTA files are properly formatted with consistent line lengths. Tools like `seqtk` or `bbtools reformat` can help standardize FASTA formats if you encounter this issue.
affects: All versions
gotchaBy default, pyfaidx truncates sequence descriptions when indexing to keep names concise. If you need to access the full FASTA header (including the description) for each sequence, you must initialize the `Fasta` object with `read_long_names=True`. This option only works with uncompressed FASTA files.
fix
Initialize `Fasta('your.fasta', read_long_names=True)` if full FASTA headers are required. For compressed files, consider decompressing or processing headers separately if full names are critical.
affects: All versions
Errors
Common errors & fixes
FastaIndexingError: Line length of fasta file is not consistent!
The FASTA file provided to `pyfaidx` has inconsistent line lengths within its sequence entries, which violates the strict FASTA format required for `.fai` indexing (samtools compatible).
fix
Ensure that all sequence lines for a given entry in your FASTA file (excluding the header line) have the same length. Tools like `seqtk` or custom scripts can often reformat FASTA files to fix this issue.
ValueError: Duplicate key "<sequence_id>"
By default, `pyfaidx` splits FASTA definition lines on the first whitespace to derive the sequence identifier (key). This error occurs when multiple sequences in the FASTA file result in the same identifier after this splitting, leading to duplicate keys in the index.
fix
When initializing `Fasta` or `Faidx`, use `read_long_names=True` to instruct `pyfaidx` to use the entire FASTA header line as the key, thereby avoiding unintended duplicates from whitespace splitting. Alternatively, ensure your FASTA headers are unique after splitting on whitespace. Example: `genes = Fasta('your.fasta', read_long_names=True)`
ModuleNotFoundError: No module named 'pyfaidx'
The `pyfaidx` library is not installed in your Python environment, or your Python interpreter cannot locate the installed package.
fix
Install the `pyfaidx` library using pip: `pip install pyfaidx`. If you are working in a virtual environment, ensure it is activated before installation.
pyfaidx.FetchError: Requested coordinates start=X end=Y are invalid.
This error occurs when attempting to fetch a subsequence with invalid coordinates, specifically when the `start` coordinate is greater than or equal to the `end` coordinate, leading to a zero or negative length sequence, especially if `strict_bounds=True` is enabled during `Fasta` or `Faidx` initialization.
fix
Adjust the `start` and `end` coordinates to ensure that `start` is strictly less than `end` (e.g., `start=1, end=10` is valid, `start=10, end=10` is invalid for a positive length). If you need to handle zero-length queries or want less strict bounds checking, initialize your `Fasta` or `Faidx` object with `strict_bounds=False`. Example: `genes = Fasta('your.fasta', strict_bounds=False)`
Upgrade
Version history
0.9.0.4latest on PyPI · released Mar 19, 2026
Audit
Dependencies
packagingrequiredUsed for version parsing and compatibility checks.
Agent activity
7 hits · last 30 days
node
6
Resources
pyfaidx — pip install pyfaidx · libregistry