Welcome to python-zlib-ng’s documentation!

Introduction

Faster zlib and gzip compatible compression and decompression by providing Python bindings for the zlib-ng library.

This package provides Python bindings for the zlib-ng library.

python-zlib-ng provides the bindings by offering three modules:

  • zlib_ng: A drop-in replacement for the zlib module that uses zlib-ng to accelerate its performance.

  • gzip_ng: A drop-in replacement for the gzip module that uses zlib_ng instead of zlib to perform its compression and checksum tasks, which improves performance.

  • gzip_ng_threaded offers an open function which returns buffered read or write streams that can be used to read and write large files while escaping the GIL using one or multiple threads. This functionality only works for streaming, seeking is not supported.

zlib_ng and gzip_ng are almost fully compatible with zlib and gzip from the Python standard library. There are some minor differences see: differences-with-zlib-and-gzip-modules.

Quickstart

The python-zlib-ng modules can be imported as follows

from zlib_ng import zlib_ng
from zlib_ng import gzip_ng
from zlib_ng import gzip_ng_threaded

zlib_ng and gzip_ng are meant to be used as drop in replacements so their api and functions are the same as the stdlib’s modules.

A full API documentation can be found on our readthedocs page.

python -m zlib_ng.gzip_ng implements a fully featured gzip-like command line application (just like python -m gzip, but better). Full usage documentation can be found on our readthedocs page.

Installation

Installation with pip

pip install zlib-ng

Installation is supported on Linux, MacOS and Windows. On most platforms wheels are provided. The installation will include a staticallly linked version of zlib-ng. If a wheel is not provided for your system the installation will build zlib-ng first in a temporary directory. Please check the zlib-ng homepage for the build requirements.

The latest development version of python-zlib-ng can be installed with:

pip install git+https://github.com/pycompression/python-zlib-ng.git

This requires having the build requirements installed. If you wish to link dynamically against a version of libz-ng installed on your system use:

PYTHON_ZLIB_NG_LINK_DYNAMIC=true pip install zlib-ng --no-binary zlib-ng

Installation via conda

Python-zlib-ng can be installed via conda, for example using the miniconda installer with a properly setup conda-forge channel. When used with bioinformatics tools setting up bioconda provides a clear set of installation instructions for conda.

python-zlib-ng is available on conda-forge and can be installed with:

conda install python-zlib-ng

This will automatically install the zlib-ng library dependency as well, since it is available on conda-forge.

python-zlib-ng as a dependency in your project

zlib-ng supports numerous platforms but not all of these have pre-built wheels available. To prevent your users from running into issues when installing your project please list a python-zlib-ng dependency as follows.

setup.cfg:

install_requires =
    zlib-ng; platform.machine == "x86_64" or platform.machine == "AMD64"

setup.py:

extras_require={
    ":platform.machine == 'x86_64' or platform.machine == 'AMD64'": ['zlib-ng']
},

Differences with zlib and gzip modules

  • Compression level 1 zlib_ng has a worse compression rate than that in zlib. For other compression levels zlib_ng compresses better.

  • gzip_ng.open returns a class GzipNGFile instead of GzipFile. Since there are differences between the compressed ratios between levels, a difference in naming was chosen to reflect this. gzip_ng.GzipFile does exist as an alias of gzip_ng.GzipNGFile for compatibility reasons.

API Documentation: zlib_ng.zlib_ng

The functions in this module allow compression and decompression using the zlib-ng library, which is a performance enhanced drop-in replacement for zlib.

adler32(string[, start]) – Compute an Adler-32 checksum. compress(data[, level]) – Compress data, with compression level 0-9 or -1. compressobj([level[, …]]) – Return a compressor object. crc32(string[, start]) – Compute a CRC-32 checksum. decompress(string,[wbits],[bufsize]) – Decompresses a compressed string. decompressobj([wbits[, zdict]]) – Return a decompressor object.

‘wbits’ is window buffer size and container format. Compressor objects support compress() and flush() methods; decompressor objects support decompress() and flush().

class zlib_ng.zlib_ng._Compress
compress(data, /)

Returns a bytes object containing compressed data.

data

Binary data to be compressed.

After calling this function, some of the input data may still be stored in internal buffers for later processing. Call the flush() method to clear these buffers.

copy()

Return a copy of the compression object.

flush(mode=4, /)

Return a bytes object containing any remaining compressed data.

mode

One of the constants Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_FINISH. If mode == Z_FINISH, the compressor object can no longer be used after calling the flush() method. Otherwise, more data can still be compressed.

class zlib_ng.zlib_ng._Decompress
copy()

Return a copy of the decompression object.

decompress(data, /, max_length=0)

Return a bytes object containing the decompressed version of the data.

data

The binary data to decompress.

max_length

The maximum allowable length of the decompressed data. Unconsumed input data will be stored in the unconsumed_tail attribute.

After calling this function, some of the input data may still be stored in internal buffers for later processing. Call the flush() method to clear these buffers.

flush(length=16384, /)

Return a bytes object containing any remaining decompressed data.

length

the initial size of the output buffer.

zlib_ng.zlib_ng.adler32(data, value=1, /)

Compute an Adler-32 checksum of data.

value

Starting value of the checksum.

The returned checksum is an integer.

zlib_ng.zlib_ng.compress(data, /, level=-1, wbits=15)

Returns a bytes object containing compressed data.

data

Binary data to be compressed.

level

Compression level, in 0-3.

wbits

The window buffer size and container format.

zlib_ng.zlib_ng.compressobj(level=-1, method=8, wbits=15, memLevel=8, strategy=0, zdict=None)

Return a compressor object.

level

The compression level (an integer in the range 0-9 or -1; default is currently equivalent to 6). Higher compression levels are slower, but produce smaller results.

method

The compression algorithm. If given, this must be DEFLATED.

wbits
  • +9 to +15: The base-two logarithm of the window size. Include a zlib container.

  • -9 to -15: Generate a raw stream.

  • +25 to +31: Include a gzip container.

memLevel

Controls the amount of memory used for internal compression state. Valid values range from 1 to 9. Higher values result in higher memory usage, faster compression, and smaller output.

strategy

Used to tune the compression algorithm. Possible values are Z_DEFAULT_STRATEGY, Z_FILTERED, and Z_HUFFMAN_ONLY.

zdict

The predefined compression dictionary - a sequence of bytes containing subsequences that are likely to occur in the input data.

zlib_ng.zlib_ng.crc32(data, value=0, /)

Compute a CRC-32 checksum of data.

value

Starting value of the checksum.

The returned checksum is an integer.

zlib_ng.zlib_ng.crc32_combine()

Combine crc1 and crc2 into a new crc that is accurate for the combined data blocks that crc1 and crc2 where calculated from.

crc1

the first crc32 checksum

crc2

the second crc32 checksum

crc2_length

the lenght of the data block crc2 was calculated from

zlib_ng.zlib_ng.decompress(data, /, wbits=15, bufsize=16384)

Returns a bytes object containing the uncompressed data.

data

Compressed data.

wbits

The window buffer size and container format.

bufsize

The initial output buffer size.

zlib_ng.zlib_ng.decompressobj(wbits=15, zdict=b'')

Return a decompressor object.

wbits

The window buffer size and container format.

zdict

The predefined compression dictionary. This must be the same dictionary as used by the compressor that produced the input data.

API-documentation: zlib_ng.gzip_ng

Similar to the stdlib gzip module. But using zlib-ng to speed up its methods.

class zlib_ng.gzip_ng.GzipNGFile(filename=None, mode=None, compresslevel=9, fileobj=None, mtime=None)

The GzipNGFile class simulates most of the methods of a file object with the exception of the truncate() method.

This class only supports opening files in binary mode. If you need to open a compressed file in text mode, use the gzip.open() function.

__init__(filename=None, mode=None, compresslevel=9, fileobj=None, mtime=None)

Constructor for the GzipNGFile class.

At least one of fileobj and filename must be given a non-trivial value.

The new class instance is based on fileobj, which can be a regular file, an io.BytesIO object, or any other object which simulates a file. It defaults to None, in which case filename is opened to provide a file object.

When fileobj is not None, the filename argument is only used to be included in the gzip file header, which may include the original filename of the uncompressed file. It defaults to the filename of fileobj, if discernible; otherwise, it defaults to the empty string, and in this case the original filename is not included in the header.

The mode argument can be any of ‘r’, ‘rb’, ‘a’, ‘ab’, ‘w’, ‘wb’, ‘x’, or ‘xb’ depending on whether the file will be read or written. The default is the mode of fileobj if discernible; otherwise, the default is ‘rb’. A mode of ‘r’ is equivalent to one of ‘rb’, and similarly for ‘w’ and ‘wb’, ‘a’ and ‘ab’, and ‘x’ and ‘xb’.

The compresslevel argument is an integer from 0 to 3 controlling the level of compression; 0 is fastest and produces the least compression, and 3 is slowest and produces the most compression. Unlike gzip.GzipFile 0 is NOT no compression. The default is 2.

The mtime argument is an optional numeric timestamp to be written to the last modification time field in the stream when compressing. If omitted or None, the current time is used.

write(data)

Write buffer b to the IO stream.

Return the number of bytes written, which is always the length of b in bytes.

Raise BlockingIOError if the buffer is full and the underlying raw stream cannot accept more data at the moment.

exception zlib_ng.gzip_ng.BadGzipFile

Exception raised in some cases for invalid gzip files.

zlib_ng.gzip_ng.GzipFile

alias of GzipNGFile

zlib_ng.gzip_ng.compress(data, compresslevel=9, *, mtime=None)

Compress data in one shot and return the compressed string. compresslevel sets the compression level in range of 0-9. mtime can be used to set the modification time. The modification time is set to the current time by default.

zlib_ng.gzip_ng.decompress(data)

Decompress a gzip compressed string in one shot. Return the decompressed string.

zlib_ng.gzip_ng.open(filename, mode='rb', compresslevel=-1, encoding=None, errors=None, newline=None)

Open a gzip-compressed file in binary or text mode. This uses the isa-l library for optimized speed.

The filename argument can be an actual filename (a str or bytes object), or an existing file object to read from or write to.

The mode argument can be “r”, “rb”, “w”, “wb”, “x”, “xb”, “a” or “ab” for binary mode, or “rt”, “wt”, “xt” or “at” for text mode. The default mode is “rb”, and the default compresslevel is 6.

For binary mode, this function is equivalent to the GzipFile constructor: GzipFile(filename, mode, compresslevel). In this case, the encoding, errors and newline arguments must not be provided.

For text mode, a GzipFile object is created, and wrapped in an io.TextIOWrapper instance with the specified encoding, error handling behavior, and line ending(s).

API-documentation: zlib_ng.gzip_ng_threaded

zlib_ng.gzip_ng_threaded.open(filename, mode='rb', compresslevel=-1, encoding=None, errors=None, newline=None, *, threads=1, block_size=1048576)

Utilize threads to read and write gzip objects and escape the GIL. Comparable to gzip.open. This method is only usable for streamed reading and writing of objects. Seeking is not supported.

threads == 0 will defer to gzip_ng.open. A threads < 0 will attempt to use the number of threads in the system.

Parameters:
  • filename – str, bytes or file-like object (supporting read or write method)

  • mode – the mode with which the file should be opened.

  • compresslevel – Compression level, only used for gzip writers.

  • encoding – Passed through to the io.TextIOWrapper, if applicable.

  • errors – Passed through to the io.TextIOWrapper, if applicable.

  • newline – Passed through to the io.TextIOWrapper, if applicable.

  • threads – If 0 will defer to gzip_ng.open, if < 0 will use all threads available to the system. Reading gzip can only use one thread.

  • block_size – Determines how large the blocks in the read/write queues are for threaded reading and writing.

Returns:

An io.BufferedReader, io.BufferedWriter, or io.TextIOWrapper, depending on the mode.

python -m zlib_ng.gzip_ng usage

A simple command line interface for the gzip_ng module. Acts like gzip.

usage: python -m zlib_ng.gzip_ng [-h]
                                 [-1 | -2 | -3 | -4 | -5 | -6 | -7 | -8 | -9 | -d]
                                 [-c | -o OUTPUT] [-n] [-f]
                                 [file]

Positional Arguments

file

Named Arguments

-1, --fast

use compression level 1

-2

use compression level 2

-3

use compression level 3

-4

use compression level 4

-5

use compression level 5

-6

use compression level 6

-7

use compression level 7

-8

use compression level 8

-9, --best

use compression level 9

-d, --decompress

Decompress the file instead of compressing.

Default: True

-c, --stdout

write on standard output

Default: False

-o, --output

Write to this output file

-n, --no-name

do not save or restore the original name and timestamp

Default: False

-f, --force

Overwrite output without prompting

Default: False

Contributing

Please make a PR or issue if you feel anything can be improved. Bug reports are also very welcome. Please report them on the github issue tracker.

Acknowledgements

This project builds upon the software and experience of many. Many thanks to:

  • The zlib-ng contributors for making the zlib-ng library.

  • The CPython contributors. Python-zlib-ng mimicks zlibmodule.c and gzip.py from the standard library to make it easier for python users to adopt it.

  • The github actions team for creating the actions CI service that enables building and testing on all three major operating systems.

Changelog

version 0.4.3

  • Fix a bug where files larger than 4GB could not be decompressed.

version 0.4.2

  • Fix a reference counting error that happened on module initialization and triggered an error in the CPython debug build.

  • Fix a setup.py error that was triggered on MacOS ARM64.

version 0.4.1

  • Fix a bug where streams that were passed to gzip_ng_threaded.open where closed.

  • Fix compatibility with Python 3.13

version 0.4.0

  • Add a gzip_ng_threaded module that contains the gzip_ng_threaded.open function. This allows using multithreaded compression as well as escaping the GIL.

  • The internal gzip_ng._GzipReader has been rewritten in C. As a result the overhead of decompressing files has significantly been reduced.

  • The gzip_ng._GzipReader in C is now used in gzip_ng.decompress. The _GzipReader also can read from objects that support the buffer protocol. This has reduced overhead significantly.

  • Fix some unclosed buffer errors in the gzip_ng CLI.

version 0.3.0

  • Source distributions on Linux now default to building with configure and make as it is faster and has less dependencies than CMake.

  • Python 3.12 support was added. Python 3.7 support was dropped as it is end of life.

  • Enabled installation on BSD

  • Update embedded zlib-ng version to 2.1.5. This comes with some speed improvements and changes with regards to the compression levels. Also several bugs were fixed. For full details checkout the zlib-ng 2.1.2 release notes as well as those for the bugfix releases 2.1.3, 2.1.4 and 2.1.5.

version 0.2.0

  • Update embedded zlib-ng version to 2.0.7

  • Escape GIL for adler32 and crc32 functions.

version 0.1.0

  • Build wheels for all three major operating systems.

  • Add a fully featured gzip application in python m zlib_ng.gzip_ng.

  • Port Cpython’s gzip module to use zlib-ng.

  • Port CPython’s zlib module to use zlib-ng.

  • Use zlib-ng version 2.0.6 as included statically linked version.