Asynchronous gzip file reading and writing for Python asyncio — aiofiles-style API, streaming text/binary modes, decompression-bomb guards, optional zlib-ng acceleration.
Project description
aiogzip ⚡️
An asynchronous API modeled after Python's gzip module for reading and
writing gzip-compressed files.
Installation
pip install aiogzip
Python 3.8 through 3.14 are supported by the 1.x release line.
Text-mode quickstart
File methods are asynchronous, and line iteration uses async for:
import aiogzip
async with aiogzip.open("events.jsonl.gz", "rt") as f:
async for line in f:
print(line)
Binary-mode quickstart
import aiogzip
async with aiogzip.open("payload.bin.gz", "wb") as f:
await f.write(b"Hello, async world!")
async with aiogzip.open("payload.bin.gz", "rb") as f:
payload = await f.read()
For small files that comfortably fit in memory, use the binary whole-file helpers:
import aiogzip
data = await aiogzip.read("payload.bin.gz")
await aiogzip.write("copy.bin.gz", data)
read() and write() load the entire decompressed or uncompressed payload
into memory. Use open() to stream large files. The existing
AsyncGzipFile() factory remains fully supported for compatibility.
For arbitrary asynchronous byte sources, compress or decompress without adapting the source to a file object:
async for data in aiogzip.decompress_chunks(compressed_source()):
await consume(data)
async for data in aiogzip.compress_chunks(raw_source(), mtime=0):
await send(data)
Complete decompression integrity validation occurs only if the iterator is consumed to the end. Compression output is incomplete if its source fails or the consumer exits early. See the async-iterable streaming guide for backpressure, limits, cancellation, metadata, and lifecycle behavior.
See the recipes for JSON Lines, untrusted input, reproducible output, append mode, seeking, cancellation recovery, and external async streams.
Why use aiogzip?
- Async file I/O built on
asyncioandaiofiles. - Binary and text modes with distinct, typed concrete classes.
- Async
read,write,readline,seek,tell,peek,readinto, and line iteration. - Interoperable gzip output, concatenated-member reads, and append support.
- Configurable gzip metadata for reproducible archives.
- Bounded decompression and rewind-cache controls for untrusted or non-seekable input.
- Pull-driven compression and decompression for
AsyncIterable[bytes]sources. - Optional zlib-ng acceleration without a required runtime dependency.
- Verified tarfile-style access patterns and
aiocsvworkflows.
Migrating from gzip
The API follows gzip, but file operations must be awaited:
| Standard library | aiogzip |
|---|---|
gzip.open(path, "rt") |
aiogzip.open(path, "rt") |
f.read() |
await f.read() |
f.readline() |
await f.readline() |
for line in f |
async for line in f |
f.seek(offset) |
await f.seek(offset) |
f.close() |
await f.close() |
Synchronous code:
import gzip
with gzip.open("events.jsonl.gz", "rt") as f:
for line in f:
process(line)
becomes asynchronous code:
import aiogzip
async with aiogzip.open("events.jsonl.gz", "rt") as f:
async for line in f:
await process(line)
Important differences and caveats:
aiogzipdefaults tocompresslevel=6;gzip.open()defaults to9. Passcompresslevel=9when that parity matters.- Paths (including
pathlib.Path) are accepted directly. Supported external asynchronous sources and destinations are passed withfilename=Noneandfileobj=...; theirread()orwrite()methods must be async. - Append modes (
"ab"and"at") create a new gzip member. Both libraries transparently read concatenated members as one decompressed stream. - An open file object is stateful and is not safe for simultaneous use by multiple tasks. Use one handle per task or serialize access.
- Gzip has no random-access index. Backward seeks rewind and replay decompression, so mixed-direction access can be O(n).
- Cancelling an executor-backed decompression can leave that reader unusable; close it and open a new handle before continuing.
Compatibility and operational behavior
aiogzip reads and writes standard gzip streams and supports text and binary
modes, tarfile-style reads, aiocsv, append mode, and concatenated members.
It is an asynchronous API modeled after gzip, not a synchronous drop-in
replacement.
- Lifecycle: Prefer
async with. When that is impractical, callawait f.open()and pair it withawait f.close()infinally. - Seeking: Backward seeks replay decompression from the start. Forward
access is fastest. Text
tell()may return a handle-bound opaque cookie when decoder state is buffered; do not persist that cookie across reopens. - Non-seekable sources: Up to 128 MiB of compressed input is cached by
default for replay. Tune
max_rewind_cache_size, or passNonefor an unbounded cache. - Untrusted input:
max_decompressed_sizecaps cumulative decompressed output for a read pass. Overflow raisesOSErrorwithout first materializing the complete expansion. - Task safety: Do not operate on one open handle concurrently from several tasks; internal codec and buffer state is mutable and intentionally unlocked.
- Cancellation: If cancellation occurs during executor-backed
decompression, later reads and seeks raise
OSError. Close and reopen the reader. A similarly cancelled compression makes that output member unusable; discard it and start a new writer. - Append mode: Each append creates another member instead of extending the existing deflate stream. Standards-compliant readers concatenate the members.
- Large writes: Gzip's 32-bit
ISIZEwraps after 4 GiB, as it does ingzip.open(). Passstrict_size=Trueto reject a member that would cross that limit. - Compression metadata:
mtimeand the embedded original filename affect output bytes. Set both explicitly when reproducibility across paths matters.
Performance and optional acceleration
Text bulk workflows are commonly faster than synchronous gzip; binary bulk
writes are near parity, while very small calls can be slower due to async
overhead. Large codec calls are offloaded to the default executor, allowing
independent streams to make progress concurrently. Line iteration and
writelines() use bounded batching.
For large UTF-8 JSON Lines files with \n terminators, the measured fast path
uses newline="\n" and chunk_size=512 * 1024. Tune memory and throughput for
your workload rather than assuming one chunk size fits every application.
Install the optional codec with:
pip install "aiogzip[fast]"
When installed, zlib-ng is selected automatically for decompression.
Compression remains on stdlib zlib so installation alone does not change gzip
bytes; pass fast_compress=True per writer to opt in. Set
AIOGZIP_ENGINE=stdlib to force stdlib behavior. Inspect the default selections
for a diagnostic report:
import aiogzip
print(aiogzip.engine_info())
The engine names are informational, not a stable machine-readable interface. See the performance guide for benchmarks and tuning guidance.
Development and contributing
The 1.x line is the last to support Python 3.8 and 3.9; aiogzip 2.0 will require Python 3.11+. Older interpreters will continue to resolve the latest compatible 1.x release from PyPI.
See the contributing guide for setup, tests, linting, typing, documentation, and benchmark workflows.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file aiogzip-1.10.0.tar.gz.
File metadata
- Download URL: aiogzip-1.10.0.tar.gz
- Upload date:
- Size: 173.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
4c53b485fd2bc6abd738dd1335366c67b46f4347fd4990fc4bfe2ee81d6d412d
|
|
| MD5 |
9b1847a5ce0db8cc3ac3c4a2973cd7a5
|
|
| BLAKE2b-256 |
c267256dbcc479de51dcce9346bbd7bd11c8211b4b1024004f7a0c0b9fc94c90
|
Provenance
The following attestation bundles were made for aiogzip-1.10.0.tar.gz:
Publisher:
publish.yml on geoff-davis/aiogzip
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
aiogzip-1.10.0.tar.gz -
Subject digest:
4c53b485fd2bc6abd738dd1335366c67b46f4347fd4990fc4bfe2ee81d6d412d - Sigstore transparency entry: 2164883472
- Sigstore integration time:
-
Permalink:
geoff-davis/aiogzip@d29a57728b646f48a974631a24c73ba8c38c30b9 -
Branch / Tag:
refs/tags/v1.10.0 - Owner: https://github.com/geoff-davis
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@d29a57728b646f48a974631a24c73ba8c38c30b9 -
Trigger Event:
push
-
Statement type:
File details
Details for the file aiogzip-1.10.0-py3-none-any.whl.
File metadata
- Download URL: aiogzip-1.10.0-py3-none-any.whl
- Upload date:
- Size: 49.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
52c20009af25d9a0db259464bc0ca04ac1ca144d62e09a1c737770c6e33328dd
|
|
| MD5 |
8014c74924fd822339b7c68405718543
|
|
| BLAKE2b-256 |
92497300600fa9a98bdc20ec9d37e50a8e9326c8a06e9c2d9e47812824ce867c
|
Provenance
The following attestation bundles were made for aiogzip-1.10.0-py3-none-any.whl:
Publisher:
publish.yml on geoff-davis/aiogzip
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
aiogzip-1.10.0-py3-none-any.whl -
Subject digest:
52c20009af25d9a0db259464bc0ca04ac1ca144d62e09a1c737770c6e33328dd - Sigstore transparency entry: 2164883508
- Sigstore integration time:
-
Permalink:
geoff-davis/aiogzip@d29a57728b646f48a974631a24c73ba8c38c30b9 -
Branch / Tag:
refs/tags/v1.10.0 - Owner: https://github.com/geoff-davis
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@d29a57728b646f48a974631a24c73ba8c38c30b9 -
Trigger Event:
push
-
Statement type: