API Reference
aiogzip exposes its supported public API from the top-level package:
AsyncGzipBinaryFile— binary-mode reader/writerAsyncGzipTextFile— text-mode reader/writeropen— recommended factory returning the right class for a mode string (acceptsr/w/a/xops with abortsuffix)AsyncGzipFile— compatibility name for the same factory behavior; it remains fully supportedread— read and decompress a complete binary stream into memorywrite— compress and write a complete bytes-like payloadEngineInfoandengine_info— immutable diagnostic information about the default compression and active decompression enginesGzipMemberInfo,GzipInfo, andinspect— validated per-member metadata and aggregate sizes from a complete decompression scanVerificationResultandverify— lightweight aggregate counts after complete integrity verificationcompressanddecompress— one-shot gzip compression and bounded decompression of a payload already in memoryIterableReader— adapter that lets anAsyncIterable[bytes]be read throughopen(..., fileobj=...)decompress_chunks— pull-driven decompression from anAsyncIterable[bytes]with bounded output chunkscompress_chunks— one-member gzip compression from anAsyncIterable[bytes]with bounded output chunksCodecOperation— the closeable iterator returned by codec state changesConcurrentOperationError— anOSErrorsubtype for operations that overlap on one single-task-owned async file handleGzipEncoderandGzipDecoder— synchronous sans-I/O state machines for transport-independent, bounded gzip encoding and decodingWithAsyncRead,WithAsyncWrite,WithAsyncReadWrite— runtime-checkable protocols describing the async file objects accepted viafileobj=ZlibEngine— type alias for zlib compressor/decompressor objects (currentlyAny; the concrete C types are not exposed in type stubs)GZIP_WBITS,GZIP_METHOD_DEFLATE,GZIP_OS_UNKNOWN, and theGZIP_FLAG_FNAME/GZIP_FLAG_FHCRC/GZIP_FLAG_FEXTRA/GZIP_FLAG_FCOMMENTheader-flag constants — useful when inspecting gzip headers alongside this library__version__
The synchronous codec is implemented in the public aiogzip.codec module.
Implementation internals live in aiogzip._common, aiogzip._binary,
aiogzip._text, aiogzip._inspection, and aiogzip._streaming. Treat those
modules as private and unstable.
import aiogzip
async with aiogzip.open("events.jsonl.gz", "rt") as stream:
async for line in stream:
print(line)
For small files that fit comfortably in memory, the whole-file helpers avoid manual lifecycle management:
Both helpers operate in binary mode and load the entire uncompressed payload
into memory. Use open() for streaming large files.
Parameters
open(), AsyncGzipFile, AsyncGzipBinaryFile and AsyncGzipTextFile take
the same parameters. The text class adds encoding, errors and newline.
open() and AsyncGzipFile choose the class from mode and pass the other
arguments to it.
| Parameter | Default | Used when | Accepted by |
|---|---|---|---|
filename |
required | reading and writing | binary and text |
mode |
"rb" ("rt" for AsyncGzipTextFile) |
reading and writing | binary and text |
chunk_size |
262144 (256 KiB) |
reading and writing | binary and text |
encoding |
"utf-8" |
reading and writing | text |
errors |
"strict" |
reading and writing | text |
newline |
None |
reading and writing | text |
compresslevel |
6 |
writing | binary and text |
mtime |
None |
writing | binary and text |
original_filename |
None |
writing | binary and text |
fileobj |
None |
reading and writing | binary and text |
closefd |
None |
reading and writing | binary and text |
max_decompressed_size |
None |
reading | binary and text |
max_rewind_cache_size |
134217728 (128 MiB) |
reading | binary and text |
strict_size |
False |
writing | binary and text |
fast_compress |
False |
writing | binary and text |
open() and AsyncGzipFile take filename and mode positionally and
everything else by keyword. The two classes also accept the other parameters
positionally, but their order differs (the text class has encoding, errors
and newline after chunk_size), so pass them by keyword. An unknown keyword
raises TypeError.
When arguments are checked
Calling open(), AsyncGzipFile or a class constructs a handle and checks
its arguments. It does not open or create anything: the file is opened by
async with or await f.open(). An invalid argument therefore raises before
any file is opened, and before any method of a fileobj is called. Each
parameter below names the exception it raises. There is one exception to
the rule: an unknown errors name is not detected until the first encoding
or decoding error.
A parameter that is used only for writing is ignored by a reader, and a parameter that is used only for reading is ignored by a writer. Values are validated in every mode, even when the parameter is otherwise ignored.
filename
A path as str, bytes or an os.PathLike object such as pathlib.Path,
or None when fileobj is given.
- With no
fileobj, the path is opened when the handle is opened. - With a
fileobj, the path is not opened. It is reported by the handle'snameproperty and, on a writer, supplies the name stored in the gzip header unlessoriginal_filenameis given. - With
filename=None,namefalls back to thenameattribute of thefileobj, if it has one.
Raises ValueError if filename and fileobj are both None, or if
filename is the empty string. Raises TypeError for any other type; if the
value looks like a file object, the message says to pass it as fileobj=.
mode
One of r (read), w (write, truncating), x (write, failing with
FileExistsError if the path exists) or a (append), with an optional b
(binary) or t (text). The characters may come in any order.
open()andAsyncGzipFiledefault to"rb". They return anAsyncGzipTextFilewhen the mode containstand anAsyncGzipBinaryFileotherwise, so"r"is binary, as ingzip.open().AsyncGzipBinaryFiledefaults to"rb"and rejectst.AsyncGzipTextFiledefaults to"rt"and rejectsb.- Append mode adds a new gzip member after the existing data. See Append mode and concatenated gzip members.
- A
+is accepted and added to the mode used to open the path. It does not make the handle both readable and writable: a handle opened withronly reads, and one opened withw,xoraonly writes.
Raises TypeError if mode is not a string. Raises ValueError if it is
empty, has no r, w, x or a, has more than one of them, repeats b,
t or +, has both b and t, or contains any other character. In a
binary mode, open() and AsyncGzipFile raise ValueError for an
encoding, errors or newline other than None.
chunk_size
A number of bytes from 1 to 134217728 (128 MiB). The default is 262144
(256 KiB), also available as AsyncGzipBinaryFile.DEFAULT_CHUNK_SIZE.
- Reading: the number of compressed bytes requested from the file or
fileobjin each read. A text reader also asks its binary layer for at most this many decompressed bytes at a time. - Writing:
writelines()joins items smaller thanchunk_sizeinto batches of at mostchunk_size(bytes in binary mode, characters in text mode) and writes larger items directly.
chunk_size is not a memory limit and does not bound what a read()
returns. See Choose the Right Chunk Size
for tuning and
Processing untrusted gzip input
for memory.
Raises TypeError if the value is not an int (a bool or float is
rejected). Raises ValueError if it is below 1 or above 128 MiB.
encoding
Text only. The name of the text encoding. The default is "utf-8", and
None means the default.
Raises ValueError for the empty string and LookupError for an unknown
encoding.
errors
Text only. The name of the codec error handler, such as "strict",
"replace", "ignore" or "surrogateescape". It applies to decoding on a
reader and to encoding on a writer. The default is "strict", and None
means the default.
With "strict", undecodable input raises UnicodeDecodeError from the read
and unencodable text raises UnicodeEncodeError from the write.
Raises TypeError if the value is neither a str nor None. The name
itself is not checked when the handle is constructed: an unknown name raises
LookupError from the first read or write that meets an encoding or decoding
error.
newline
Text only. One of None, "", "\n", "\r" or "\r\n", with the same
meaning as in io.TextIOWrapper. The default is None.
newline |
Reading | Writing |
|---|---|---|
None |
\r\n and \r are returned as \n; lines end at \n |
\n is written as os.linesep |
"" |
nothing is translated; lines end at \n, \r or \r\n |
nothing is translated |
"\n" |
nothing is translated; lines end at \n |
nothing is translated |
"\r" |
nothing is translated; lines end at \r |
\n is written as \r |
"\r\n" |
nothing is translated; lines end at \r\n |
\n is written as \r\n |
Because newline=None writes \n as os.linesep, the same program produces
\r\n on Windows and \n elsewhere. Pass newline="" or newline="\n" to
write the text unchanged on every platform.
Raises ValueError for any other string.
compresslevel
Used when writing. An integer from -1 to 9. The default is 6. 0 stores
the data without compression, 1 is fastest, 9 compresses most, and -1
selects the compression library's default level.
Raises TypeError if the value is not an int (a bool or float is
rejected) and ValueError if it is outside -1 to 9. A reader validates
compresslevel when the handle is constructed, then ignores it.
mtime
Writing only. The timestamp stored in the gzip header, in seconds since the
epoch, from 0 to 4294967295 (2³² − 1). A float is truncated to an
integer. The default, None, stores the current time when the handle is
opened. Pass a fixed value such as mtime=0 for
reproducible gzip output.
Raises TypeError if the value is not an int or float (a bool is
rejected). Raises ValueError if it is negative, infinite or NaN, or if
its truncated value is above 2³² − 1 (so 4294967295.9 is accepted as
4294967295).
A reader checks the value and then ignores it. The mtime property of a
reader reports the timestamp read from the stream; see
Live member timestamps.
original_filename
Writing only. The name stored in the gzip header's FNAME field, as str
or bytes. The default, None, takes the name from filename; if
filename is also None, no name is stored.
In either case the stored name is the final path component with a trailing
.gz removed, so original_filename="/a/b/c.tar.gz" stores c.tar. A str
is stored as Latin-1; a name that cannot be encoded as Latin-1 is left out.
Pass original_filename="" to store no name. See
Reproducible gzip output.
Raises TypeError if the value is not str or bytes (an os.PathLike
object is rejected) and ValueError if it contains a NUL. A reader checks
the value and then ignores it.
fileobj
An already-open asynchronous file object to read from or write to in place of
a path. A reader needs an async read(size) method that returns bytes; a
writer needs an async write(data) method that returns the number of bytes
it accepted. close(), seek() and seekable() are used when present. The
default is None.
A synchronous file object such as io.BytesIO is not rejected when the
handle is constructed. It raises TypeError (on a writer) when the handle is
opened, or OSError (on a reader) at the first read. See
External async file objects.
closefd
Whether closing the handle also closes fileobj. It must be True, False
or None.
None(the default) andFalse: thefileobjis left open.True: thefileobjis closed with the handle.
closefd has no effect on a file that the handle opened from a path. That
file is always closed with the handle. See
Opening ownership for what happens when
opening fails.
Raises TypeError for any value other than True, False or None; see
Exact boolean options.
max_decompressed_size
Reading only. The largest number of decompressed bytes the reader will
produce in one pass through the stream, as a positive integer. The limit is
in bytes in text mode too. The default, None, sets no limit. Crossing the
limit raises OSError from the read. A stream of exactly the limit is
accepted. Set it when reading untrusted input; see Safety limits and
Processing untrusted gzip input.
Raises TypeError if the value is not an int or None (a bool or
float is rejected) and ValueError if it is below 1. A writer checks the
value and then ignores it.
max_rewind_cache_size
Reading only, and only when the source cannot seek. To let such a reader
seek() backward, the handle keeps the compressed bytes it has read so that
it can replay them. This parameter is the largest size of that cache in
bytes, as a positive integer. The default is 134217728 (128 MiB). None
sets no limit.
When the next chunk would take the cache over the limit, the cache is
discarded. From then on seekable() returns False and a backward seek()
raises OSError; forward reading is unaffected. A source that can seek is
rewound directly and uses no cache. See Seeking.
Raises TypeError if the value is not an int or None (a bool or
float is rejected) and ValueError if it is below 1. A writer checks the
value and then ignores it.
strict_size
Writing only. The gzip trailer stores the uncompressed size of a member
modulo 2³². With False (the default), a larger member is written and its
stored size wraps, as the format allows. With True, a write that would
take the member past 4294967295 bytes raises OSError.
Raises TypeError for any value other than True or False. A reader
checks the value and then ignores it.
fast_compress
Writing only. With True, the writer compresses with zlib-ng if the
aiogzip[fast] extra is installed. The output is valid gzip but is not
byte-for-byte identical to the default output. If zlib-ng is not available,
the writer warns (UserWarning) when the handle is constructed and uses the
standard library's zlib. The default is False. See
Optional Faster Codec.
Raises TypeError for any value other than True or False. A reader
checks the value, then ignores it and does not warn.
Parameters of the whole-file helpers
read(), write(), inspect() and verify() take filename positionally
and a subset of the parameters above by keyword. Each has the meaning,
default, range and exceptions given above. The helpers are coroutines, so an
invalid argument raises when the call is awaited.
| Function | Keyword parameters |
|---|---|
read(filename) |
chunk_size, fileobj, closefd, max_decompressed_size, max_rewind_cache_size |
write(filename, data) |
chunk_size, compresslevel, mtime, original_filename, fileobj, closefd, strict_size, fast_compress |
inspect(filename) |
chunk_size, fileobj, closefd, max_decompressed_size |
verify(filename) |
chunk_size, fileobj, closefd, max_decompressed_size |
write() takes data as bytes, bytearray or memoryview.
compress_chunks(), decompress_chunks(), GzipEncoder and GzipDecoder
document their own parameters in the reference below.
Exact boolean options
Public boolean configuration uses exact built-in booleans. fast_compress,
strict_size, and the codec's collect_member_info accept only True or
False. closefd accepts True, False, or None; None keeps the ownership
default, closing path-opened resources while preserving caller-supplied file
objects. Integer substitutes such as 0 and 1, strings, and custom truthy or
falsy objects raise TypeError with the parameter name.
The contract is identical across AsyncGzipBinaryFile,
AsyncGzipTextFile, open(), AsyncGzipFile, the whole-file helpers, the
async-iterable compressor, and the synchronous codec. Validation happens
before file acquisition, external file methods, source iteration, zlib-ng
warning logic, or codec operation reservation. This contract is part of the
public API covered by the stability policy; it is not a
security fix.
For writers, strict_size=False preserves gzip's normal modulo-2³² ISIZE;
strict_size=True rejects a member crossing that field's range.
fast_compress=False keeps stdlib-compatible output, while
fast_compress=True opts that writer into zlib-ng when available and otherwise
emits the documented fallback warning. Explicit closefd=False preserves a
caller-supplied file object; closefd=True closes it with the wrapper.
Live member timestamps
In read mode, AsyncGzipBinaryFile.mtime is None until the shared gzip
parser completes the first valid member header. It then holds that header's
32-bit timestamp. Each later valid header in a concatenated stream replaces
the value, including repeated timestamps and zero.
The property follows parser progress rather than only the bytes returned to
the caller. If one compressed source chunk contains several members, decoder
read-ahead can leave mtime at the last header in that chunk even when the
current read() returned bytes from an earlier member. This means the exact
point at which the property advances can depend on chunk_size and source read
boundaries.
A complete header updates mtime before its DEFLATE body or trailer is
validated, so a later body, CRC, or ISIZE error does not roll the timestamp
back. An invalid or incomplete header does not commit; a rejected first header
therefore leaves mtime=None, while a rejected later header preserves the
last valid value. After a rewind, the old value remains visible until a header
is parsed again. AsyncGzipTextFile.mtime delegates to the same binary reader
state.
Synchronous codec
Use GzipEncoder and GzipDecoder when an application owns a synchronous or
custom transport and needs aiogzip's framing, concatenated-member traversal,
integrity validation, and output limits without any I/O or executor policy.
Each state-changing call returns a lazy CodecOperation that must be exhausted
before another operation begins. Its idempotent close() method provides
deterministic cleanup when a caller exits before exhaustion.
import aiogzip
encoder = aiogzip.GzipEncoder(mtime=0)
wire = b"".join(encoder.start())
wire += b"".join(encoder.feed(b"payload"))
wire += b"".join(encoder.finish())
decoder = aiogzip.GzipDecoder()
payload = b"".join(decoder.feed(wire)) + b"".join(decoder.finish())
Warning: Decoder output can precede its trailer. Integrity is established only after the operation returned by
finish()is exhausted.
The public codec API is frozen for the 2.0 line. See the stability policy and synchronous codec guide for the compatibility boundary, constructor validation, immutable input snapshots, lifecycle hazards, thread safety, and error behavior.
With collect_member_info=True, GzipDecoder.members contains immutable
records only for members whose trailers validated. Those completed records
remain available if a later member fails or the codec is explicitly discarded;
the incomplete member is absent and the codec remains unusable. Retained
records prove only those members, not the entire concatenated stream. Use
decoder.finished as the whole-stream completion indicator. Collection is
opt-in because its memory use grows with the member count.
aiogzip.codec.CodecOperation
Bases: Iterator[bytes], Protocol
A lazy codec operation with deterministic abandonment cleanup.
Exhaust the operation to complete it. Calling :meth:close before
exhaustion releases captured work and makes the owning codec unusable;
closing an exhausted or already closed operation has no effect.
aiogzip.codec.GzipEncoder
GzipEncoder(*, compresslevel: int = 6, mtime: int | float | None = None, original_filename: str | bytes | None = None, fast_compress: bool = False, strict_size: bool = False, output_chunk_size: int = 256 * 1024)
Bases: _CodecBase
Incrementally encode exactly one complete gzip member.
Methods return bounded lazy iterators. The iterator from each operation
must be exhausted before another method is called. Explicitly closing an
incomplete operation makes the encoder unusable; dropping it leaves the
encoder reserved until :meth:discard is called.
This class performs no I/O or executor offload and is not thread-safe.
Source code in src/aiogzip/codec.py
feed
Consume one immutable input snapshot and emit compressed chunks.
Source code in src/aiogzip/codec.py
finish
Finalize DEFLATE and lazily emit the gzip trailer exactly once.
Source code in src/aiogzip/codec.py
flush
Perform a non-finalizing Z_SYNC_FLUSH operation.
Source code in src/aiogzip/codec.py
start
Start the member and lazily emit its gzip header exactly once.
Source code in src/aiogzip/codec.py
aiogzip.codec.GzipDecoder
GzipDecoder(*, output_chunk_size: int = 256 * 1024, max_decompressed_size: int | None = None, collect_member_info: bool = False)
Bases: _CodecBase
Incrementally decode and validate zero or more gzip members.
Payload bytes may be emitted before their member trailer is available, so
integrity is established only after :meth:finish is exhausted. Completed
metadata is retained only when collect_member_info=True. Records for
trailer-validated members survive a later failure or explicit discard;
:attr:finished remains the whole-stream validation indicator.
Methods return bounded lazy iterators that must be exhausted. This class performs no I/O or executor offload and is not thread-safe.
Source code in src/aiogzip/codec.py
members
property
Collected completed members, retained after failure or discard.
uncompressed_size
property
Decompressed bytes accounted during operation advancement.
feed
Accept compressed bytes and lazily emit bounded decoded output.
Source code in src/aiogzip/codec.py
finish
Prove that all accepted input forms a complete valid gzip stream.
Engine diagnostics
engine_info() reports the default compression implementation and the active
decompression implementation without exposing internal codec objects:
Compression is reported as stdlib-zlib because that is the default even when
zlib-ng is installed. A writer created with fast_compress=True opts that
individual stream into zlib-ng; that per-stream choice is not reflected by
engine_info(). The strings are human-readable diagnostics and are not a
stable machine-readable feature-detection API.
Inspection and verification
inspect() scans and validates the complete gzip stream but discards its
decompressed payload. It returns one immutable GzipMemberInfo per member,
including exact compressed offsets and sizes, actual uncompressed sizes,
literal trailer ISIZE values, and optional header metadata. Header mtime=0
is preserved as 0; FNAME and FCOMMENT use deterministic Latin-1 decoding.
import aiogzip
info = await aiogzip.inspect("events.gz", max_decompressed_size=1024**3)
for member in info.members:
print(member.index, member.compressed_offset, member.uncompressed_size)
verify() performs the same complete structural, deflate, CRC-32, and ISIZE
validation without retaining per-member metadata:
Successful return means the entire stream is valid. Corruption raises
gzip.BadGzipFile; I/O and decompression-limit failures raise OSError.
Zero-byte input is valid and returns zero members and zero sizes. NUL padding
after a valid member is accepted and included in the aggregate compressed size;
other trailing data is treated as a malformed next member.
inspect() holds every member's record until it returns, so its memory grows
with the number of members; verify() keeps only running totals. While it
parses a header, inspect() (like GzipDecoder with
collect_member_info=True) buffers each FNAME, FCOMMENT and FEXTRA field
whole and keeps it in the member's record. FEXTRA is at most 64 KiB by the
format, but FNAME and FCOMMENT are bounded only by the header limit: any
single gzip header larger than 128 MiB raises gzip.BadGzipFile.
max_decompressed_size does not count header bytes. Scanning untrusted input
with many members or very large header fields can therefore use substantial
memory; prefer verify() when per-member metadata is not needed.
Cancelling inspect() or verify() waits for any native open, read or close
already running in a worker thread to finish before the cancellation
propagates. A native read still queued for a worker is skipped and never
touches the source. A file opened by path is closed once, and only after its last
read; if that close itself fails, the failure is reported as below. A
borrowed fileobj is closed only when closefd=True.
If the scan fails and closing the source then fails too, the scan's error is raised with the close failure attached as a note. A cancellation or interrupt that arrives during that close outranks an ordinary scan error and propagates, with the scan error as its context. If the scan succeeded, a close failure is raised as before.
Async-iterable decompression
decompress_chunks() accepts only an asynchronous iterable of bytes and
returns an AsyncIterator[bytes]. Empty source chunks are ignored, yielded
chunks are non-empty, and output_chunk_size is a strict upper bound.
async for data in aiogzip.decompress_chunks(
compressed_source(),
output_chunk_size=64 * 1024,
max_decompressed_size=1024**3,
):
await consume(data)
The stream is validated incrementally. Payload can be yielded before its final
CRC and trailer are available, so complete integrity validation occurs only
when iteration ends normally. Corruption raises gzip.BadGzipFile, output
limit violations raise OSError, invalid source items raise TypeError, and
source exceptions and cancellation propagate. See the
streaming guide for backpressure and lifecycle details.
compress_chunks() accepts an asynchronous iterable of uncompressed bytes
and yields exactly one gzip member. It emits the header promptly, before
requesting the first source item. Empty sources therefore produce a valid empty
member rather than zero bytes.
async for data in aiogzip.compress_chunks(
raw_source(),
mtime=0,
output_chunk_size=64 * 1024,
):
await send(data)
The trailer is emitted only after the source ends normally. If the source
raises, compression is cancelled, or output consumption stops early, bytes
already yielded form an incomplete member and must be discarded. Compression
levels, metadata, strict_size, and fast_compress match the file writer.
When writing through an external asynchronous fileobj, its write() method
may accept fewer bytes than requested as long as it returns the accepted byte
count. aiogzip retries short writes until the complete gzip block is written.
A zero-progress or otherwise invalid count raises OSError.
Reading from an async iterable
decompress_chunks() turns an asynchronous iterable of compressed bytes
into decompressed chunks. To read lines, text or sized binary reads from such
a source, wrap it in IterableReader and pass that as fileobj:
reader = aiogzip.IterableReader(compressed_source())
async with aiogzip.open(None, "rt", fileobj=reader, closefd=True) as stream:
async for line in stream:
print(line)
The source can be any asynchronous iterable of bytes, bytearray or
memoryview: an HTTP response body, an object-store download, an async
generator. Empty items are skipped. The reader pulls one item at a time and
only when a read needs more input, so it applies backpressure to the source
and never reads ahead.
- Closing. With
closefd=Truethe gzip handle closes the reader when it closes, and the reader calls the iterator'saclose(), so an async generator's cleanup runs even when you stop early. With the default, the reader is left open and you close it withawait reader.aclose(). - Seeking. The reader cannot seek.
seek()backwards andrewind()replay compressed input from the handle's rewind cache, whichmax_rewind_cache_sizebounds. - Failures. If the source raises, or a read is cancelled while waiting for the next item, the reader cannot tell whether input was lost. It becomes unusable and the gzip handle reports its stream as broken; reopen from a new source. See source failures and cancellation.
- Limits.
max_decompressed_sizeworks as for any other source.
reader.tell() is the number of compressed bytes handed out so far. A reader
serves one consumer and one gzip handle.
aiogzip.IterableReader
Present an asynchronous iterable of bytes as a readable fileobj.
Pass an instance as fileobj to :func:aiogzip.open to read lines,
text or sized binary reads from a source that offers only async
iteration, such as an HTTP response body or an object-store download::
reader = aiogzip.IterableReader(response.aiter_raw())
async with aiogzip.open(None, "rt", fileobj=reader, closefd=True) as f:
async for line in f:
...
Items may be bytes, bytearray or memoryview. Empty items are
skipped. The source is consumed one item at a time, only when a read
needs more input, so it is never read ahead.
The reader cannot seek. A gzip handle reading from it rewinds through its
rewind cache, which max_rewind_cache_size bounds.
If the source raises, or a read is cancelled while waiting for the next
item, the reader becomes unusable: it cannot know whether the source
consumed input, so later reads raise OSError and :meth:tell raises
ValueError. A gzip handle reading from it then reports its stream as
broken, as for any custom source in that state.
A reader serves one consumer. It is not safe to share between tasks.
Source code in src/aiogzip/_iterable_reader.py
aclose
async
close
async
Close the reader and the source iterator.
Calls the iterator's aclose() when it has one, so an async
generator's cleanup runs. If iteration never started, an aclose()
on the source itself is used. Closing again after a close that
succeeded has no effect. If the source's aclose() raises or is
cancelled, the reader stays closed to reads, the error propagates and
a later close() calls aclose() again.
Source code in src/aiogzip/_iterable_reader.py
read
async
Read up to size bytes.
A positive size returns between 1 and size bytes: whatever is
left of the current source item, without waiting for another one. It
returns b"" only at the end of the source. size of None
or a negative number reads to the end of the source.
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If the reader is closed. |
OSError
|
If the reader is unusable after an earlier failure. |
RuntimeError
|
If another read is already in progress. |
Source code in src/aiogzip/_iterable_reader.py
tell
Return the number of bytes handed out by :meth:read so far.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the reader is closed, or unusable after its source failed or a read was cancelled. |
Source code in src/aiogzip/_iterable_reader.py
In-memory compression and decompression
compress() and decompress() are coroutines for a payload that is already
in memory, such as an HTTP body, a queue message or a cache value. They are
the asynchronous counterparts of gzip.compress() and gzip.decompress().
blob = await aiogzip.compress(payload, mtime=0)
data = await aiogzip.decompress(blob, max_decompressed_size=50 * 2**20)
compress() returns one gzip member and takes the options of
compress_chunks(): compresslevel, mtime, original_filename,
fast_compress and strict_size. Two defaults differ from
gzip.compress(): the level is 6 on every Python version (the standard
library used 9 before Python 3.15), and mtime=None stores the current
time (the standard library stores 0 from Python 3.14). Pass mtime=0 for
reproducible output. No file name is stored unless one is given.
decompress() decodes every concatenated member, accepts trailing zero
padding and returns b"" for empty input, as gzip.decompress() does. It
returns only after every member's CRC and length have been checked.
Corrupt or truncated input raises gzip.BadGzipFile. With
max_decompressed_size set, a larger stream raises OSError as soon as it
proves larger. It inflates one byte past the limit to prove it, and no more.
await asyncio.to_thread(gzip.decompress, data) has no such bound.
The default is None, no limit, as everywhere else in the API; set it for
untrusted input.
Both accept bytes, bytearray or memoryview. A mutable buffer is copied
once before any work starts, so changing it afterwards does not affect the
result. Invalid arguments raise when the call is awaited.
The codec work does not hold the event loop for long. compress() runs a
payload of 256 KiB or more in the default executor and a smaller one inline.
decompress() inflates in bounded steps and yields to other tasks between
them, with the first step of an input of 1 MiB or more in the executor. A
cancelled call returns after the step in progress has finished. Two plain
memory copies do run on the event loop and grow with the payload: the copy
of a bytearray or memoryview input, and the join that builds the result.
aiogzip.codec.compress() and aiogzip.codec.decompress() are synchronous
twins with the same options, for code outside an event loop. They run
entirely in the calling thread and, like the rest of the codec, accept
bytes only.
import aiogzip.codec
blob = aiogzip.codec.compress(b"payload", mtime=0)
data = aiogzip.codec.decompress(blob, max_decompressed_size=50 * 2**20)
Both pairs hold the whole input and the whole output in memory, and the
output briefly twice while it is joined into one object. For a
payload that arrives in pieces use compress_chunks() and
decompress_chunks(); for a file use open().
aiogzip.compress
async
compress(data: Union[bytes, bytearray, memoryview], *, compresslevel: int = 6, mtime: Optional[Union[int, float]] = None, original_filename: Optional[Union[str, bytes]] = None, fast_compress: bool = False, strict_size: bool = False) -> bytes
Compress a payload held in memory into one gzip member.
The asynchronous counterpart of gzip.compress(). A payload of 256 KiB
or more is compressed in the default executor; a smaller one is
compressed inline, where a thread hop would cost more than the work.
Copying a mutable data and assembling the result are plain memory
copies made on the event loop. aiogzip.codec.compress() is the
synchronous twin.
An invalid argument raises when the call is awaited.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Union[bytes, bytearray, memoryview]
|
The payload, as |
required |
compresslevel
|
int
|
The compression level, from |
6
|
mtime
|
Optional[Union[int, float]]
|
The timestamp stored in the gzip header, from |
None
|
original_filename
|
Optional[Union[str, bytes]]
|
The name stored in the gzip header. The default,
|
None
|
fast_compress
|
bool
|
With |
False
|
strict_size
|
bool
|
With |
False
|
Returns:
| Type | Description |
|---|---|
bytes
|
One complete gzip member. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If an option is outside its supported range. |
OSError
|
If compression fails or |
Source code in src/aiogzip/__init__.py
aiogzip.decompress
async
decompress(data: Union[bytes, bytearray, memoryview], *, max_decompressed_size: Optional[int] = None) -> bytes
Decompress a complete gzip stream held in memory.
The asynchronous counterpart of gzip.decompress(), with an output
limit. It decodes every concatenated member, accepts trailing zero
padding and returns b"" for empty input. The result is returned only
after every member's CRC and length have been checked.
Inflation runs in bounded steps that yield to the event loop. Copying a
mutable data and assembling the result are plain memory copies made
on the event loop. With max_decompressed_size set, the call stops and
raises as soon as the stream proves larger: it inflates one byte past
the limit to prove it, and no more. The result is assembled with one
join, so the peak is about twice the output size.
aiogzip.codec.decompress() is the synchronous twin.
An invalid argument raises when the call is awaited.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Union[bytes, bytearray, memoryview]
|
The whole gzip stream, as |
required |
max_decompressed_size
|
Optional[int]
|
The largest number of decompressed bytes to
accept; a larger stream raises |
None
|
Returns:
| Type | Description |
|---|---|
bytes
|
The decompressed payload of all members. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If the limit is not positive. |
BadGzipFile
|
If the stream is malformed, corrupt or truncated. |
OSError
|
If the output would exceed |
Source code in src/aiogzip/__init__.py
aiogzip.codec.compress
compress(data: bytes, *, compresslevel: int = 6, mtime: int | float | None = None, original_filename: str | bytes | None = None, fast_compress: bool = False, strict_size: bool = False) -> bytes
Compress data into one complete gzip member, synchronously.
This is :class:GzipEncoder driven to completion in the calling thread.
The options have the meaning, default and range they have there. For a
payload that arrives in pieces, or output that should not be held in
memory at once, use the encoder itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
bytes
|
The payload. Exact |
required |
compresslevel
|
int
|
The compression level, from |
6
|
mtime
|
int | float | None
|
The gzip header timestamp. |
None
|
original_filename
|
str | bytes | None
|
The name stored in the gzip header, if any. |
None
|
fast_compress
|
bool
|
With |
False
|
strict_size
|
bool
|
With |
False
|
Returns:
| Type | Description |
|---|---|
bytes
|
One gzip member. |
Source code in src/aiogzip/codec.py
aiogzip.codec.decompress
Decompress a complete gzip stream held in memory, synchronously.
This is :class:GzipDecoder driven to completion in the calling thread.
Like gzip.decompress(), it decodes every concatenated member, accepts
trailing zero padding and returns b"" for empty input. Unlike it, the
output can be bounded: with max_decompressed_size set, the call stops
inflating and raises once the stream proves larger: it inflates one byte
past the limit to prove it, and no more. The result is assembled with one
join, so the peak is about twice the output size.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
bytes
|
The whole gzip stream. Exact |
required |
max_decompressed_size
|
int | None
|
The largest number of decompressed bytes to
accept. The default, |
None
|
Returns:
| Type | Description |
|---|---|
bytes
|
The decompressed payload of all members. |
Raises:
| Type | Description |
|---|---|
BadGzipFile
|
If the stream is malformed, corrupt or truncated. |
OSError
|
If the output would exceed |
Source code in src/aiogzip/codec.py
Safety limits
Set max_decompressed_size=<bytes> when reading untrusted gzip data. The
limit applies to cumulative decompressed output for the current pass through
the stream. Each inflate call is restricted to the remaining allowance plus
one byte, so an over-limit member raises OSError without first materializing
its full expansion in memory. Rewinding resets the accounting because the new
read pass starts again at byte zero.
Text encodings
AsyncGzipTextFile keeps one incremental encoder for the lifetime of a write
stream. Multiple write() or writelines() calls therefore produce one
continuous encoded byte stream, including for stateful encodings such as
UTF-16, UTF-32, and ISO-2022-JP. Any final encoder shift sequence is written
before the gzip member's final block and trailer.
Both binary and text writelines() collect small inputs into bounded
chunk_size batches before compression. Inputs larger than a batch are written
directly, so generators remain streaming and memory use stays bounded.
Byte-count and compression tuning parameters are integer-only:
chunk_size, compresslevel, max_decompressed_size, and
max_rewind_cache_size reject floats, strings, and booleans with TypeError.
seek() and tell() in text mode
AsyncGzipBinaryFile.tell() returns the current position as a plain non-negative count of decompressed bytes, and seek(offset) accepts any such offset.
AsyncGzipTextFile.tell() returns one of two things:
- A plain non-negative offset (decompressed bytes) when the stream is at a clean boundary — no buffered text, the decoder holds no partial multibyte sequence, and there is no pending
\r. This is the same value the underlying binary layer reports (await f.buffer.tell()). - An opaque cookie (a negative integer) otherwise. The cookie encodes the decoder state needed to resume mid-character, mid-line, or mid-
\r\n, so round-trippingseek(await f.tell())is exact.
seek() accepts both: a non-negative argument is treated as a plain offset (decompression is replayed forward to that byte — from the current position when the decoder is at a clean boundary at or behind the target, from the start of the stream otherwise), and a negative argument is decoded as a cookie.
Cookies are bound to the handle that minted them
Warning. A text
tell()cookie is valid only on the same open handle. This differs fromio.TextIOWrapperandgzip.open("rt"), whosetell()cookies encode only decoder state and remain usable after re-opening the same file. Anaiogziptext cookie embeds a random per-instance nonce, whichseek()validates; a cookie from a different handle (or from before the file was re-opened) is rejected withOSErrorrather than silently restoring the wrong decoder state. Do not persist cookies across processes or re-opens — persist a plain offset instead.
Resumable processing recipe
Because cookies are not portable, checkpoint progress as a plain offset taken at a line boundary, where the decoder is guaranteed clean (\n is single-byte, so it never splits a multibyte character). Drive the binary layer — which splits lines without the text layer's read-ahead — so await f.tell() is an exact decompressed byte offset, then resume in a new process by opening in "rt" and seeking to that offset.
A forward plain seek() is O(n) in the target offset: gzip has no random access, so aiogzip replays decompressed bytes up to the offset. Checkpoint at a coarse granularity if that cost matters. See Resumable text processing for the full worked example.
aiogzip
Async gzip file reader/writer public API.
AsyncGzipBinaryFile
AsyncGzipBinaryFile(filename: _Filename, mode: str = 'rb', chunk_size: int = DEFAULT_CHUNK_SIZE, compresslevel: int = 6, mtime: Optional[Union[int, float]] = None, original_filename: Optional[Union[str, bytes]] = None, fileobj: Optional[Union[WithAsyncRead, WithAsyncWrite, WithAsyncReadWrite, _WithAsyncBinaryWrite]] = None, closefd: Optional[bool] = None, max_decompressed_size: Optional[int] = None, max_rewind_cache_size: Optional[int] = _MAX_CHUNK_SIZE, strict_size: bool = False, fast_compress: bool = False)
An asynchronous gzip file reader/writer for binary data.
This class provides async gzip compression/decompression for binary data. Its API is modeled after gzip.open() in binary mode, but it is not a drop-in replacement: methods that perform I/O are coroutines and must be awaited.
Features:
- Full compatibility with gzip.open() file format
- Binary mode only (no text encoding/decoding)
- Async context manager support
- Configurable chunk size for performance tuning
Basic usage:
# Write binary data
async with AsyncGzipBinaryFile("data.gz", "wb") as f:
await f.write(b"Hello, World!")
# Read binary data
async with AsyncGzipBinaryFile("data.gz", "rb") as f:
data = await f.read() # Returns bytes
# Imperative lifecycle when `async with` is impractical
f = AsyncGzipBinaryFile("data.gz", "rb")
await f.open()
try:
data = await f.read()
finally:
await f.close()
Interoperability with gzip.open():
# Files created by AsyncGzipBinaryFile can be read by gzip.open()
async with AsyncGzipBinaryFile("data.gz", "wb") as f:
await f.write(b"data")
with gzip.open("data.gz", "rb") as f:
data = f.read()
Constructing a handle checks its arguments and opens nothing; the file
is opened by async with or await f.open(). Pass every argument
after mode by keyword. Each parameter is described in full under
"Parameters" in the API reference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
_Filename
|
Path of the gzip file, as |
required |
mode
|
str
|
One of |
'rb'
|
chunk_size
|
int
|
Reading: the number of compressed bytes requested from
the file or |
DEFAULT_CHUNK_SIZE
|
compresslevel
|
int
|
Writing only. The compression level, from |
6
|
mtime
|
Optional[Union[int, float]]
|
Writing only. The timestamp stored in the gzip header, in
seconds since the epoch, from |
None
|
original_filename
|
Optional[Union[str, bytes]]
|
Writing only. The name stored in the gzip header,
as |
None
|
fileobj
|
Optional[Union[WithAsyncRead, WithAsyncWrite, WithAsyncReadWrite, _WithAsyncBinaryWrite]]
|
An already-open asynchronous file object to use in place
of a path. A reader needs |
None
|
closefd
|
Optional[bool]
|
Whether closing the handle also closes |
None
|
max_decompressed_size
|
Optional[int]
|
Reading only. The largest number of
decompressed bytes the reader will produce in one pass through
the stream; crossing it raises |
None
|
max_rewind_cache_size
|
Optional[int]
|
Reading only, when the source cannot seek.
The largest number of compressed bytes kept so that the reader
can |
_MAX_CHUNK_SIZE
|
strict_size
|
bool
|
Writing only. With |
False
|
fast_compress
|
bool
|
Writing only. With |
False
|
Source code in src/aiogzip/_binary.py
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 | |
mtime
property
Return the timestamp from the most recently parsed member header.
The value is None until the first complete valid header is read.
Decoder read-ahead can advance it beyond the bytes returned by the
current read call when concatenated members share one source chunk.
name
property
Return the name of the file.
This property provides compatibility with the standard file API.
Returns the filename passed to the constructor, or falls back to the
underlying file object's name attribute when available.
Returns:
| Type | Description |
|---|---|
Union[str, bytes, Path, None]
|
The filename as it was given (str, bytes, Path or another |
Union[str, bytes, Path, None]
|
os.PathLike object), or None if no name is available. |
__aenter__
async
__aexit__
async
__aexit__(exc_type: Optional[type], exc_val: Optional[BaseException], exc_tb: Optional[Any]) -> None
Exit the context manager, flushing and closing the file.
Source code in src/aiogzip/_binary.py
__aiter__
__anext__
async
Return the next line from the binary stream.
close
async
Flushes any remaining compressed data and closes the file.
Source code in src/aiogzip/_binary.py
detach
fileno
Return the underlying file descriptor number.
Source code in src/aiogzip/_binary.py
flush
async
Flush any buffered compressed data to the file.
In write/append mode, this forces any buffered compressed data to be written to the underlying file. Note that this does NOT write the gzip trailer - use close() for that.
In read mode, this is a no-op for compatibility with the file API.
Examples:
async with AsyncGzipBinaryFile("file.gz", "wb") as f: await f.write(b"Hello") await f.flush() # Ensure data is written await f.write(b" World")
Source code in src/aiogzip/_binary.py
isatty
Return True if the underlying stream is interactive.
Source code in src/aiogzip/_binary.py
open
async
Open the file for I/O and return self.
This performs the same initialization as entering the async context
manager, for callers who prefer an explicit try/finally over async
with::
f = AsyncGzipBinaryFile("data.gz", "rb")
await f.open()
try:
data = await f.read()
finally:
await f.close()
Raises:
| Type | Description |
|---|---|
ValueError
|
if the file is already open, or has already been closed (a closed instance cannot be reopened, matching io objects). |
Source code in src/aiogzip/_binary.py
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 | |
peek
async
Return up to size bytes without advancing the read position.
Source code in src/aiogzip/_binary.py
raw
read
async
Reads and decompresses binary data from the file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size
|
int
|
Number of bytes to read (-1 for all remaining data) |
-1
|
Returns:
| Type | Description |
|---|---|
bytes
|
bytes |
Examples:
async with AsyncGzipBinaryFile("file.gz", "rb") as f: data = await f.read() # Returns bytes partial = await f.read(100) # Returns first 100 bytes
Source code in src/aiogzip/_binary.py
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 | |
read1
async
Read up to size bytes with at most one data-producing fill.
A single compressed chunk can decode to nothing (e.g. while consuming
the gzip header), so fills repeat until at least one byte is available;
like stdlib gzip's read1(), an empty result means EOF.
Source code in src/aiogzip/_binary.py
readinto
async
Read bytes directly into a pre-allocated, writable buffer.
Fills the caller's buffer straight from the decompression buffer,
avoiding the intermediate bytes object that delegating to read()
would allocate. Returns the number of bytes written (0 at EOF).
Source code in src/aiogzip/_binary.py
readinto1
async
Read directly into the buffer with at most one data-producing fill.
Like read1() but writes straight into the caller's buffer, avoiding
the intermediate bytes object. A single compressed chunk can decode
to nothing (e.g. while consuming the gzip header), so fills repeat
until at least one byte is available; the result is still capped at one
buffer's worth of decoded data. Returns the number of bytes written
(0 only at EOF), so while await f.readinto1(buf): ... is safe.
Source code in src/aiogzip/_binary.py
readline
async
Read and return one line from the binary stream.
Source code in src/aiogzip/_binary.py
readlines
async
Read and return a list of lines from the binary stream.
Source code in src/aiogzip/_binary.py
seek
async
Move to a new file position, mirroring gzip.GzipFile semantics.
Source code in src/aiogzip/_binary.py
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 | |
tell
async
Return the current uncompressed file position.
Source code in src/aiogzip/_binary.py
truncate
write
async
Compresses and writes binary data to the file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Union[bytes, bytearray, memoryview]
|
Bytes to write |
required |
Examples:
async with AsyncGzipBinaryFile("file.gz", "wb") as f: await f.write(b"Hello, World!") # Bytes input
Source code in src/aiogzip/_binary.py
writelines
async
Write bytes-like lines in bounded batches without adding separators.
Source code in src/aiogzip/_binary.py
AsyncGzipTextFile
AsyncGzipTextFile(filename: _Filename, mode: str = 'rt', chunk_size: int = AsyncGzipBinaryFile.DEFAULT_CHUNK_SIZE, encoding: Optional[str] = 'utf-8', errors: Optional[str] = 'strict', newline: Union[str, None] = None, compresslevel: int = 6, mtime: Optional[Union[int, float]] = None, original_filename: Optional[Union[str, bytes]] = None, fileobj: Optional[Union[WithAsyncRead, WithAsyncWrite, WithAsyncReadWrite, _WithAsyncBinaryWrite]] = None, closefd: Optional[bool] = None, max_decompressed_size: Optional[int] = None, max_rewind_cache_size: Optional[int] = _MAX_CHUNK_SIZE, strict_size: bool = False, fast_compress: bool = False)
An asynchronous gzip file reader/writer for text data.
This class wraps AsyncGzipBinaryFile and provides text mode operations with proper UTF-8 handling for multi-byte characters.
Features:
- Full compatibility with gzip.open() file format
- Text mode with automatic encoding/decoding
- Proper handling of multi-byte UTF-8 characters
- Line-by-line iteration support
- Async context manager support
Basic usage:
# Write text data
async with AsyncGzipTextFile("data.gz", "wt") as f:
await f.write("Hello, World!") # String input
# Read text data
async with AsyncGzipTextFile("data.gz", "rt") as f:
text = await f.read() # Returns string
# Line-by-line iteration
async with AsyncGzipTextFile("data.gz", "rt") as f:
async for line in f:
print(line.strip())
# Imperative lifecycle when `async with` is impractical
f = AsyncGzipTextFile("data.gz", "rt")
await f.open()
try:
text = await f.read()
finally:
await f.close()
Constructing a handle checks its arguments and opens nothing; the file
is opened by async with or await f.open(). Pass every argument
after mode by keyword. Each parameter is described in full under
"Parameters" in the API reference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
_Filename
|
Path of the gzip file, as |
required |
mode
|
str
|
One of |
'rt'
|
chunk_size
|
int
|
Reading: the number of compressed bytes requested from
the file or |
DEFAULT_CHUNK_SIZE
|
encoding
|
Optional[str]
|
The name of the text encoding. The default is
|
'utf-8'
|
errors
|
Optional[str]
|
The name of the codec error handler, such as |
'strict'
|
newline
|
Union[str, None]
|
One of |
None
|
compresslevel
|
int
|
Writing only. The compression level, from |
6
|
mtime
|
Optional[Union[int, float]]
|
Writing only. The timestamp stored in the gzip header, in
seconds since the epoch, from |
None
|
original_filename
|
Optional[Union[str, bytes]]
|
Writing only. The name stored in the gzip header,
as |
None
|
fileobj
|
Optional[Union[WithAsyncRead, WithAsyncWrite, WithAsyncReadWrite, _WithAsyncBinaryWrite]]
|
An already-open asynchronous file object to use in place
of a path. A reader needs |
None
|
closefd
|
Optional[bool]
|
Whether closing the handle also closes |
None
|
max_decompressed_size
|
Optional[int]
|
Reading only. The largest number of
decompressed bytes (not characters) the reader will produce in
one pass through the stream; crossing it raises |
None
|
max_rewind_cache_size
|
Optional[int]
|
Reading only, when the source cannot seek.
The largest number of compressed bytes kept so that the reader
can |
_MAX_CHUNK_SIZE
|
strict_size
|
bool
|
Writing only. With |
False
|
fast_compress
|
bool
|
Writing only. With |
False
|
Source code in src/aiogzip/_text.py
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 | |
mtime
property
Return the latest parsed member timestamp from the binary layer.
name
property
Return the name of the file.
This property provides compatibility with the standard file API.
Returns the filename passed to the constructor, or falls back to the
underlying file object's name attribute when available.
Returns:
| Type | Description |
|---|---|
Union[str, bytes, Path, None]
|
The filename as it was given (str, bytes, Path or another |
Union[str, bytes, Path, None]
|
os.PathLike object), or None if no name is available. |
newlines
property
Return newline types observed while reading, like TextIOWrapper.
__aenter__
async
__aexit__
async
__aexit__(exc_type: Optional[type], exc_val: Optional[BaseException], exc_tb: Optional[Any]) -> None
Exit the context manager, flushing and closing the file.
Source code in src/aiogzip/_text.py
__aiter__
__anext__
async
Return the next line from the file.
Source code in src/aiogzip/_text.py
close
async
Closes the file.
Source code in src/aiogzip/_text.py
detach
flush
async
Flush any buffered data to the file.
In write/append mode, this forces any buffered text to be encoded and written to the underlying binary file.
In read mode, this is a no-op for compatibility with the file API.
Examples:
async with AsyncGzipTextFile("file.gz", "wt") as f: await f.write("Hello") await f.flush() # Ensure data is written await f.write(" World")
Source code in src/aiogzip/_text.py
isatty
iter_batches
Iterate over the file in batches of complete lines.
Equivalent to calling readlines(hint) in a loop until it returns an
empty list, but as an async iterator::
async with aiogzip.open("file.gz", "rt") as f:
async for batch in f.iter_batches():
for line in batch:
process(line)
Each yielded batch is a non-empty list of lines (trailing newlines
included, exactly as readlines returns them); iteration ends at
EOF. Batching amortizes the per-line await overhead of async
for line in f and is measurably faster on line-dense files, while
keeping memory bounded by roughly hint characters per batch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hint
|
int
|
Positive batch size hint in characters. A batch is complete
once the lines collected so far total at least |
DEFAULT_BATCH_HINT
|
Returns:
| Type | Description |
|---|---|
AsyncIterator[List[str]]
|
AsyncIterator[List[str]]: An async iterator of line batches. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If hint is not an integer. |
ValueError
|
If hint is not positive. |
Source code in src/aiogzip/_text.py
open
async
Open the file for I/O and return self.
This performs the same initialization as entering the async context
manager, for callers who prefer an explicit try/finally over async
with::
f = AsyncGzipTextFile("data.txt.gz", "rt")
await f.open()
try:
text = await f.read()
finally:
await f.close()
Raises:
| Type | Description |
|---|---|
ValueError
|
if the file is already open, or has already been closed (a closed instance cannot be reopened, matching io objects). |
Source code in src/aiogzip/_text.py
read
async
Reads and decodes text data from the file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size
|
int
|
Number of characters to read (-1 for all remaining data) |
-1
|
Returns:
| Type | Description |
|---|---|
str
|
str |
Examples:
async with AsyncGzipTextFile("file.gz", "rt") as f: text = await f.read() # Returns string partial = await f.read(100) # Returns first 100 chars as string
Source code in src/aiogzip/_text.py
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 | |
readline
async
Read and return one line from the file.
A line is defined as text ending with a newline character ('\n'). If the file ends without a newline, the last line is returned without one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
limit
|
int
|
Maximum number of characters to return. Stops at newline, EOF, or once the limit is reached (matching TextIOBase semantics). |
-1
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The next line from the file, including the newline if present. Returns empty string at EOF. |
Examples:
async with AsyncGzipTextFile("file.gz", "rt") as f: line = await f.readline() # Read one line while line: print(line.rstrip()) line = await f.readline()
Source code in src/aiogzip/_text.py
2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 | |
readlines
async
Read and return a list of lines from the file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hint
|
int
|
Optional size hint. If given and greater than 0, reading stops once the decoded lines returned so far total at least hint characters (the line that crosses the hint is still returned whole). If hint is -1, None or not given, all remaining lines are read. |
-1
|
Returns:
| Type | Description |
|---|---|
List[str]
|
List[str]: A list of lines from the file, each including any trailing |
List[str]
|
newline character. |
Examples:
async with AsyncGzipTextFile("file.gz", "rt") as f: lines = await f.readlines() # Read all lines for line in lines: print(line.rstrip())
With size hint
async with AsyncGzipTextFile("file.gz", "rt") as f: lines = await f.readlines(1024) # Read ~1KB of lines
Source code in src/aiogzip/_text.py
truncate
write
async
Encodes and writes text data to the file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
str
|
String to write |
required |
Examples:
async with AsyncGzipTextFile("file.gz", "wt") as f: await f.write("Hello, World!") # String input
Source code in src/aiogzip/_text.py
writelines
async
Write a list of lines to the file.
Note that newlines are not added automatically; each string in the iterable should include its own line terminator if desired.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lines
|
Iterable[str]
|
An iterable of strings to write. |
required |
Examples:
async with AsyncGzipTextFile("file.gz", "wt") as f: await f.writelines(["line1\n", "line2\n", "line3\n"])
From a generator
async with AsyncGzipTextFile("file.gz", "wt") as f: await f.writelines(f"{i}\n" for i in range(100))
Source code in src/aiogzip/_text.py
2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 | |
CodecOperation
Bases: Iterator[bytes], Protocol
A lazy codec operation with deterministic abandonment cleanup.
Exhaust the operation to complete it. Calling :meth:close before
exhaustion releases captured work and makes the owning codec unusable;
closing an exhausted or already closed operation has no effect.
ConcurrentOperationError
Bases: OSError
Raised when overlapping operations use one file handle concurrently.
Await the operation that already owns the handle before retrying the rejected call. One file handle is intentionally single-task-owned.
EngineInfo
dataclass
Human-readable codec selections used by aiogzip by default.
GzipDecoder
GzipDecoder(*, output_chunk_size: int = 256 * 1024, max_decompressed_size: int | None = None, collect_member_info: bool = False)
Bases: _CodecBase
Incrementally decode and validate zero or more gzip members.
Payload bytes may be emitted before their member trailer is available, so
integrity is established only after :meth:finish is exhausted. Completed
metadata is retained only when collect_member_info=True. Records for
trailer-validated members survive a later failure or explicit discard;
:attr:finished remains the whole-stream validation indicator.
Methods return bounded lazy iterators that must be exhausted. This class performs no I/O or executor offload and is not thread-safe.
Source code in src/aiogzip/codec.py
members
property
Collected completed members, retained after failure or discard.
uncompressed_size
property
Decompressed bytes accounted during operation advancement.
feed
Accept compressed bytes and lazily emit bounded decoded output.
Source code in src/aiogzip/codec.py
finish
Prove that all accepted input forms a complete valid gzip stream.
GzipEncoder
GzipEncoder(*, compresslevel: int = 6, mtime: int | float | None = None, original_filename: str | bytes | None = None, fast_compress: bool = False, strict_size: bool = False, output_chunk_size: int = 256 * 1024)
Bases: _CodecBase
Incrementally encode exactly one complete gzip member.
Methods return bounded lazy iterators. The iterator from each operation
must be exhausted before another method is called. Explicitly closing an
incomplete operation makes the encoder unusable; dropping it leaves the
encoder reserved until :meth:discard is called.
This class performs no I/O or executor offload and is not thread-safe.
Source code in src/aiogzip/codec.py
feed
Consume one immutable input snapshot and emit compressed chunks.
Source code in src/aiogzip/codec.py
finish
Finalize DEFLATE and lazily emit the gzip trailer exactly once.
Source code in src/aiogzip/codec.py
flush
Perform a non-finalizing Z_SYNC_FLUSH operation.
Source code in src/aiogzip/codec.py
start
Start the member and lazily emit its gzip header exactly once.
Source code in src/aiogzip/codec.py
GzipInfo
dataclass
GzipMemberInfo
dataclass
GzipMemberInfo(index: int, compressed_offset: int, compressed_size: int, uncompressed_size: int, mtime: int, original_filename: str | None, comment: str | None, extra: bytes | None, flags: int, crc32: int, trailer_isize: int)
Validated metadata and sizes for one gzip member.
mtime preserves the literal unsigned header value, including zero.
Filename and comment fields are decoded one-to-one with Latin-1; absent
fields are None, while present empty fields are empty strings.
IterableReader
Present an asynchronous iterable of bytes as a readable fileobj.
Pass an instance as fileobj to :func:aiogzip.open to read lines,
text or sized binary reads from a source that offers only async
iteration, such as an HTTP response body or an object-store download::
reader = aiogzip.IterableReader(response.aiter_raw())
async with aiogzip.open(None, "rt", fileobj=reader, closefd=True) as f:
async for line in f:
...
Items may be bytes, bytearray or memoryview. Empty items are
skipped. The source is consumed one item at a time, only when a read
needs more input, so it is never read ahead.
The reader cannot seek. A gzip handle reading from it rewinds through its
rewind cache, which max_rewind_cache_size bounds.
If the source raises, or a read is cancelled while waiting for the next
item, the reader becomes unusable: it cannot know whether the source
consumed input, so later reads raise OSError and :meth:tell raises
ValueError. A gzip handle reading from it then reports its stream as
broken, as for any custom source in that state.
A reader serves one consumer. It is not safe to share between tasks.
Source code in src/aiogzip/_iterable_reader.py
aclose
async
close
async
Close the reader and the source iterator.
Calls the iterator's aclose() when it has one, so an async
generator's cleanup runs. If iteration never started, an aclose()
on the source itself is used. Closing again after a close that
succeeded has no effect. If the source's aclose() raises or is
cancelled, the reader stays closed to reads, the error propagates and
a later close() calls aclose() again.
Source code in src/aiogzip/_iterable_reader.py
read
async
Read up to size bytes.
A positive size returns between 1 and size bytes: whatever is
left of the current source item, without waiting for another one. It
returns b"" only at the end of the source. size of None
or a negative number reads to the end of the source.
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If the reader is closed. |
OSError
|
If the reader is unusable after an earlier failure. |
RuntimeError
|
If another read is already in progress. |
Source code in src/aiogzip/_iterable_reader.py
tell
Return the number of bytes handed out by :meth:read so far.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the reader is closed, or unusable after its source failed or a read was cancelled. |
Source code in src/aiogzip/_iterable_reader.py
VerificationResult
dataclass
Aggregate counts returned after successful integrity verification.
WithAsyncRead
Bases: Protocol
Protocol for async file-like objects that can be read.
WithAsyncReadWrite
Bases: Protocol
Protocol for async file-like objects that can be read and written.
WithAsyncWrite
Bases: Protocol
Protocol for async file-like objects that can be written.
AsyncGzipFile
AsyncGzipFile(filename: _Filename, mode: _TextMode, *, chunk_size: int = ..., encoding: Optional[str] = ..., errors: Optional[str] = ..., newline: Optional[str] = ..., compresslevel: int = ..., mtime: Optional[Union[int, float]] = ..., original_filename: Optional[Union[str, bytes]] = ..., fileobj: _FileObj = ..., closefd: Optional[bool] = ..., max_decompressed_size: Optional[int] = ..., max_rewind_cache_size: Optional[int] = ..., strict_size: bool = ..., fast_compress: bool = ...) -> AsyncGzipTextFile
AsyncGzipFile(filename: _Filename, mode: _BinaryMode = ..., *, chunk_size: int = ..., compresslevel: int = ..., mtime: Optional[Union[int, float]] = ..., original_filename: Optional[Union[str, bytes]] = ..., fileobj: _FileObj = ..., closefd: Optional[bool] = ..., max_decompressed_size: Optional[int] = ..., max_rewind_cache_size: Optional[int] = ..., strict_size: bool = ..., fast_compress: bool = ...) -> AsyncGzipBinaryFile
AsyncGzipFile(filename: _Filename, mode: str = 'rb', **kwargs: Any) -> Union[AsyncGzipBinaryFile, AsyncGzipTextFile]
Factory function that returns the appropriate AsyncGzip class based on mode.
open() is the recommended entry point and has identical behavior.
AsyncGzipFile is the older name, kept for existing code.
The call checks its arguments and opens nothing; the file is opened by
async with or await f.open(). Each parameter is described in
full under "Parameters" in the API reference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
_Filename
|
Path of the gzip file, as |
required |
mode
|
str
|
One of |
'rb'
|
**kwargs
|
Any
|
Passed by keyword to the class: |
{}
|
Returns:
| Type | Description |
|---|---|
Union[AsyncGzipBinaryFile, AsyncGzipTextFile]
|
An |
Source code in src/aiogzip/__init__.py
compress
async
compress(data: Union[bytes, bytearray, memoryview], *, compresslevel: int = 6, mtime: Optional[Union[int, float]] = None, original_filename: Optional[Union[str, bytes]] = None, fast_compress: bool = False, strict_size: bool = False) -> bytes
Compress a payload held in memory into one gzip member.
The asynchronous counterpart of gzip.compress(). A payload of 256 KiB
or more is compressed in the default executor; a smaller one is
compressed inline, where a thread hop would cost more than the work.
Copying a mutable data and assembling the result are plain memory
copies made on the event loop. aiogzip.codec.compress() is the
synchronous twin.
An invalid argument raises when the call is awaited.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Union[bytes, bytearray, memoryview]
|
The payload, as |
required |
compresslevel
|
int
|
The compression level, from |
6
|
mtime
|
Optional[Union[int, float]]
|
The timestamp stored in the gzip header, from |
None
|
original_filename
|
Optional[Union[str, bytes]]
|
The name stored in the gzip header. The default,
|
None
|
fast_compress
|
bool
|
With |
False
|
strict_size
|
bool
|
With |
False
|
Returns:
| Type | Description |
|---|---|
bytes
|
One complete gzip member. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If an option is outside its supported range. |
OSError
|
If compression fails or |
Source code in src/aiogzip/__init__.py
compress_chunks
compress_chunks(source: AsyncIterable[bytes], *, compresslevel: int = 6, mtime: Optional[Union[int, float]] = None, original_filename: Optional[Union[str, bytes]] = None, fast_compress: bool = False, strict_size: bool = False, output_chunk_size: int = AsyncGzipBinaryFile.DEFAULT_CHUNK_SIZE) -> AsyncIterator[bytes]
Incrementally compress an asynchronous byte iterable as one gzip member.
The header is emitted before the first source item is requested. Output
chunks are non-empty and no larger than output_chunk_size.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
AsyncIterable[bytes]
|
Asynchronous iterable yielding uncompressed |
required |
compresslevel
|
int
|
Compression level from |
6
|
mtime
|
Optional[Union[int, float]]
|
Optional gzip header timestamp. Use zero for reproducibility. |
None
|
original_filename
|
Optional[Union[str, bytes]]
|
Optional filename stored in the gzip header. |
None
|
fast_compress
|
bool
|
Opt into zlib-ng compression when available. |
False
|
strict_size
|
bool
|
Reject payloads exceeding gzip's 32-bit |
False
|
output_chunk_size
|
int
|
Strict upper bound for each yielded chunk. |
DEFAULT_CHUNK_SIZE
|
Returns:
| Type | Description |
|---|---|
AsyncIterator[bytes]
|
A single-consumer asynchronous iterator containing one gzip member. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If call-time arguments or a source item have invalid types. |
ValueError
|
If an option is outside its supported range. |
OSError
|
If compression fails or |
Source code in src/aiogzip/__init__.py
decompress
async
decompress(data: Union[bytes, bytearray, memoryview], *, max_decompressed_size: Optional[int] = None) -> bytes
Decompress a complete gzip stream held in memory.
The asynchronous counterpart of gzip.decompress(), with an output
limit. It decodes every concatenated member, accepts trailing zero
padding and returns b"" for empty input. The result is returned only
after every member's CRC and length have been checked.
Inflation runs in bounded steps that yield to the event loop. Copying a
mutable data and assembling the result are plain memory copies made
on the event loop. With max_decompressed_size set, the call stops and
raises as soon as the stream proves larger: it inflates one byte past
the limit to prove it, and no more. The result is assembled with one
join, so the peak is about twice the output size.
aiogzip.codec.decompress() is the synchronous twin.
An invalid argument raises when the call is awaited.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Union[bytes, bytearray, memoryview]
|
The whole gzip stream, as |
required |
max_decompressed_size
|
Optional[int]
|
The largest number of decompressed bytes to
accept; a larger stream raises |
None
|
Returns:
| Type | Description |
|---|---|
bytes
|
The decompressed payload of all members. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If the limit is not positive. |
BadGzipFile
|
If the stream is malformed, corrupt or truncated. |
OSError
|
If the output would exceed |
Source code in src/aiogzip/__init__.py
decompress_chunks
decompress_chunks(source: AsyncIterable[bytes], *, output_chunk_size: int = AsyncGzipBinaryFile.DEFAULT_CHUNK_SIZE, max_decompressed_size: Optional[int] = None) -> AsyncIterator[bytes]
Incrementally decompress gzip bytes from an asynchronous iterable.
Output chunks are non-empty and no larger than output_chunk_size.
Complete CRC and trailer validation occurs only when the returned iterator
is consumed to completion.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
AsyncIterable[bytes]
|
Asynchronous iterable yielding compressed |
required |
output_chunk_size
|
int
|
Strict upper bound for each yielded chunk. |
DEFAULT_CHUNK_SIZE
|
max_decompressed_size
|
Optional[int]
|
Optional cumulative decompressed-byte limit. |
None
|
Returns:
| Type | Description |
|---|---|
AsyncIterator[bytes]
|
A single-consumer asynchronous iterator of decompressed |
Raises:
| Type | Description |
|---|---|
TypeError
|
If call-time arguments or a source item have invalid types. |
ValueError
|
If a size argument is outside its supported range. |
BadGzipFile
|
If the consumed gzip stream is malformed or corrupt. |
OSError
|
If the cumulative output limit is exceeded. |
Source code in src/aiogzip/__init__.py
engine_info
Return the default compression and active decompression engines.
Compression remains on stdlib zlib unless a writer opts into zlib-ng with
fast_compress=True. The returned strings are intended for diagnostics,
not machine-readable feature detection.
Source code in src/aiogzip/_engine.py
inspect
async
inspect(filename: _Filename, *, chunk_size: int = AsyncGzipBinaryFile.DEFAULT_CHUNK_SIZE, fileobj: _ReadFileObj = None, closefd: Optional[bool] = None, max_decompressed_size: Optional[int] = None) -> GzipInfo
Inspect and validate every member in a complete gzip stream.
This performs a full decompression scan while discarding payload bytes.
mtime preserves the literal header value, including zero; filename and
comment metadata use Latin-1 decoding.
Source code in src/aiogzip/__init__.py
open
open(filename: _Filename, mode: _TextMode, *, chunk_size: int = ..., encoding: Optional[str] = ..., errors: Optional[str] = ..., newline: Optional[str] = ..., compresslevel: int = ..., mtime: Optional[Union[int, float]] = ..., original_filename: Optional[Union[str, bytes]] = ..., fileobj: _FileObj = ..., closefd: Optional[bool] = ..., max_decompressed_size: Optional[int] = ..., max_rewind_cache_size: Optional[int] = ..., strict_size: bool = ..., fast_compress: bool = ...) -> AsyncGzipTextFile
open(filename: _Filename, mode: _BinaryMode = ..., *, chunk_size: int = ..., compresslevel: int = ..., mtime: Optional[Union[int, float]] = ..., original_filename: Optional[Union[str, bytes]] = ..., fileobj: _FileObj = ..., closefd: Optional[bool] = ..., max_decompressed_size: Optional[int] = ..., max_rewind_cache_size: Optional[int] = ..., strict_size: bool = ..., fast_compress: bool = ...) -> AsyncGzipBinaryFile
open(filename: _Filename, mode: str = 'rb', **kwargs: Any) -> Union[AsyncGzipBinaryFile, AsyncGzipTextFile]
Open a gzip stream in binary or text mode.
This is the recommended public entry point. AsyncGzipFile remains
available and has identical behavior.
The call checks its arguments and opens nothing; the file is opened by
async with or await f.open(). Each parameter is described in
full under "Parameters" in the API reference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
_Filename
|
Path of the gzip file, as |
required |
mode
|
str
|
One of |
'rb'
|
**kwargs
|
Any
|
Passed by keyword to the class: |
{}
|
Returns:
| Type | Description |
|---|---|
Union[AsyncGzipBinaryFile, AsyncGzipTextFile]
|
An |
Source code in src/aiogzip/__init__.py
read
async
read(filename: _Filename, *, chunk_size: int = AsyncGzipBinaryFile.DEFAULT_CHUNK_SIZE, fileobj: _ReadFileObj = None, closefd: Optional[bool] = None, max_decompressed_size: Optional[int] = None, max_rewind_cache_size: Optional[int] = _MAX_CHUNK_SIZE) -> bytes
Read and decompress an entire gzip stream into memory.
The keyword parameters have the meaning, default, range and exceptions
documented on AsyncGzipBinaryFile. An invalid argument raises when
the call is awaited.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
_Filename
|
Path of the gzip file, or |
required |
chunk_size
|
int
|
The number of compressed bytes requested from the file
or |
DEFAULT_CHUNK_SIZE
|
fileobj
|
_ReadFileObj
|
An already-open asynchronous file object, with an
|
None
|
closefd
|
Optional[bool]
|
|
None
|
max_decompressed_size
|
Optional[int]
|
The largest number of decompressed bytes to
accept; a larger stream raises |
None
|
max_rewind_cache_size
|
Optional[int]
|
The largest number of compressed bytes kept
for rewinding a source that cannot seek. The default is
134217728 (128 MiB), and |
_MAX_CHUNK_SIZE
|
Returns:
| Type | Description |
|---|---|
bytes
|
The whole decompressed payload. |
Source code in src/aiogzip/__init__.py
verify
async
verify(filename: _Filename, *, chunk_size: int = AsyncGzipBinaryFile.DEFAULT_CHUNK_SIZE, fileobj: _ReadFileObj = None, closefd: Optional[bool] = None, max_decompressed_size: Optional[int] = None) -> VerificationResult
Validate a complete gzip stream and return aggregate counts.
Successful return means every header, deflate payload, CRC, and ISIZE
was valid. Invalid input and resource-limit failures raise instead.
Source code in src/aiogzip/__init__.py
write
async
write(filename: _Filename, data: Union[bytes, bytearray, memoryview], *, chunk_size: int = AsyncGzipBinaryFile.DEFAULT_CHUNK_SIZE, compresslevel: int = 6, mtime: Optional[Union[int, float]] = None, original_filename: Optional[Union[str, bytes]] = None, fileobj: _WriteFileObj = None, closefd: Optional[bool] = None, strict_size: bool = False, fast_compress: bool = False) -> None
Compress and write an entire bytes-like payload to a gzip stream.
The keyword parameters have the meaning, default, range and exceptions
documented on AsyncGzipBinaryFile. An invalid argument raises when
the call is awaited.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
_Filename
|
Path of the gzip file to create or truncate, or |
required |
data
|
Union[bytes, bytearray, memoryview]
|
The payload, as |
required |
chunk_size
|
int
|
Checked as for the file classes: from 1 to 134217728 (128 MiB). The default is 262144 (256 KiB). |
DEFAULT_CHUNK_SIZE
|
compresslevel
|
int
|
The compression level, from |
6
|
mtime
|
Optional[Union[int, float]]
|
The timestamp stored in the gzip header, from |
None
|
original_filename
|
Optional[Union[str, bytes]]
|
The name stored in the gzip header. The default,
|
None
|
fileobj
|
_WriteFileObj
|
An already-open asynchronous file object, with an
|
None
|
closefd
|
Optional[bool]
|
|
None
|
strict_size
|
bool
|
With |
False
|
fast_compress
|
bool
|
With |
False
|