Brotli Compression Library

1.2.0 · active · verified Sat Mar 28

Python bindings for the Brotli compression library. It offers high-performance lossless compression, often achieving better ratios than gzip, particularly for text-based data. The library's releases are typically synchronized with updates to the underlying C Brotli reference implementation.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic one-shot compression and decompression, as well as a simple streaming compression and decompression using `brotli.Compressor` and `brotli.Decompressor`. It also shows how to handle the `output_buffer_limit` introduced in v1.2.0 for security.

import brotli

# Example data (must be bytes)
original_data = b"This is some sample text data that we want to compress. It's repetitive and will benefit from Brotli's algorithm."

# Compress data with default quality (11, highest compression)
# quality can range from 0 (fastest) to 11 (highest compression ratio)
compressed_data = brotli.compress(original_data, quality=5)

print(f"Original size: {len(original_data)} bytes")
print(f"Compressed size: {len(compressed_data)} bytes")

# Decompress data
decompressed_data = brotli.decompress(compressed_data)

print(f"Decompressed size: {len(decompressed_data)} bytes")
print(f"Data matches original: {original_data == decompressed_data}")

# Example of streaming compression
compressor = brotli.Compressor(quality=4)
streaming_compressed = b''

for i in range(3):
    chunk = b'chunk ' + str(i).encode() + b' of data\n'
    streaming_compressed += compressor.process(chunk)
streaming_compressed += compressor.finish()

print(f"\nStreaming compressed size: {len(streaming_compressed)} bytes")

# Example of streaming decompression (with output_buffer_limit for safety)
decompressor = brotli.Decompressor()
streaming_decompressed = b''
max_output_len = 1024 # Set a reasonable limit

try:
    # process might raise brotli.error if output_buffer_limit is exceeded
    for chunk in [streaming_compressed]: # In real usage, this would be chunks of compressed data
        streaming_decompressed += decompressor.process(chunk, output_buffer_limit=max_output_len)
    streaming_decompressed += decompressor.finish()
    print(f"Streaming decompressed size: {len(streaming_decompressed)} bytes")
except brotli.error as e:
    print(f"Decompression error: {e}")
    print("Output buffer limit likely exceeded or corrupted data.")

view raw JSON →