Registry / serialization / brotli

brotli

JSON →
library1.2.0pypypi✓ verified 25d ago

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.

pip install brotli
INSTALL
IMPORT
SIG · BROTLI
B
brotli
serializationpythonv1.2.0
Install
1.8s avg
Import
Disk
20MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.2.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.000s · 21.5MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 1.8s · import 0.000s · 23MB
20MB installed
● package 20MB
Code
Verified usage

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

brotli
import brotli
compress
brotli.compress(data)
For one-shot compression of bytes.
decompress
brotli.decompress(compressed_data)
For one-shot decompression of bytes.
Compressor
compressor = brotli.Compressor()
For streaming compression.
Decompressor
decompressor = brotli.Decompressor()
For streaming decompression.
error
try: ... except brotli.error: ...
The exception raised for compression/decompression failures or invalid arguments.

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.")
Debug
Known issues
breakingOlder versions (<= 1.1.0) are vulnerable to Denial of Service (DoS) attacks via 'decompression bombs' (e.g., highly compressed zero-filled data expanding to excessive sizes), leading to memory exhaustion. Version 1.2.0 introduces `Decompressor::can_accept_more_data` and an optional `output_buffer_limit` argument to `Decompressor::process` to mitigate this.
fix
Upgrade to brotli v1.2.0 or newer. For streaming decompression, actively use the `output_buffer_limit` parameter in `Decompressor.process()` and handle `brotli.error` if the limit is exceeded.
affects: <= 1.1.0
gotchaVersions of brotli prior to v1.0.9 were vulnerable to an integer overflow in the decoder when processing input chunks larger than 2GiB (CVE-2020-8927).
fix
Upgrade to brotli v1.0.9 or newer.
affects: <= 1.0.8
gotchaAttempting to decompress data that was not compressed with Brotli will raise a `brotli.error` exception. Ensure the input data is valid Brotli compressed data.
fix
Wrap decompression calls in a `try...except brotli.error` block to gracefully handle invalid input.
affects: All
gotchaWhen using `brotli.Compressor` for streaming compression, it's crucial to call the `.finish()` method at the end of the data stream. Failing to do so will result in an incomplete or corrupted compressed output, as buffered data may not be flushed.
fix
Always call `compressor.finish()` after feeding all data chunks to `compressor.process()` to ensure all remaining data is emitted.
affects: All
gotchaWhen interacting with files, Brotli operates on raw bytes. Files must be opened in binary mode (`'rb'` for reading, `'wb'` for writing) to avoid `TypeError` or unexpected corruption.
fix
Always open files for Brotli operations with `b` in the mode string (e.g., `open('file.br', 'wb')`).
affects: All
gotchaHTTP client libraries like `requests` and `urllib3` automatically detect and decompress Brotli (and other) encodings if the `brotli` library is installed. If you attempt to manually decompress content that has already been automatically decompressed, it will result in `brotli.error`.
fix
Check the `Content-Encoding` header or the documentation of your HTTP client to determine if automatic decompression is occurring before attempting manual decompression.
affects: All
breakingThe `finish()` method is exclusive to the `brotli.Compressor` object for flushing remaining compressed data. The `brotli.Decompressor` object does not have a `finish()` method. Attempting to call it will result in an `AttributeError`.
fix
Do not call `finish()` on a `brotli.Decompressor` object. For streaming decompression, feed all compressed data chunks into `decompressor.process()` until all data is decompressed.
affects: All
gotchaThe `brotli.Decompressor` object does not have a `finish()` method. Unlike `brotli.Compressor`, there is no explicit 'finish' step for decompressors. All decompressed output is returned by `decompressor.process()` as input chunks are fed, or when the final `process()` call is made with remaining input.
fix
Remove calls to `decompressor.finish()`. Ensure all output from `decompressor.process()` is collected during streaming decompression. When all input is processed, any remaining decompressed data will have been emitted by the last `decompressor.process()` call.
affects: All
Errors
Common errors & fixes
ModuleNotFoundError: No module named '_brotli' OR ImportError: DLL load failed while importing _brotli: The specified module could not be found.
This error typically occurs on Windows when the C extension for brotli is not properly built or found, often due to missing Visual C++ Build Tools or an incorrect Python environment.
fix
Ensure you have the Microsoft Visual C++ Build Tools installed (available through Visual Studio Installer). Then, try uninstalling and reinstalling brotli: `pip uninstall brotli` followed by `pip install brotli`. It is also recommended to use a virtual environment.
AttributeError: module 'brotli' has no attribute 'error'
This error usually arises from a conflict between the `brotli` package and `brotlipy` (or `brotlicffi`), where another library's `import brotli` statement resolves to a different or older implementation that lacks the `error` exception class.
fix
First, try updating or reinstalling `brotli`: `pip install --upgrade brotli`. If the issue persists, explicitly uninstall both `brotli` and `brotlipy`/`brotlicffi` and then reinstall only `brotli`: `pip uninstall brotli brotlipy brotlicffi` then `pip install brotli`.
ERROR: Could not build wheels for brotli
This installation error indicates that pip was unable to compile the C source code for the brotli Python bindings, most commonly due to missing C/C++ compiler tools or other build dependencies.
fix
On Windows, install the Microsoft Visual C++ Build Tools. On Linux, ensure you have build essentials (e.g., `sudo apt-get install build-essential` or `sudo yum groupinstall 'Development Tools'`). Then retry `pip install brotli`.
brotli.brotli.Error: Decompression error: incomplete compressed stream.
This error occurs when attempting to decompress data that is corrupted, truncated, or not valid Brotli compressed data.
fix
Verify the integrity and completeness of the Brotli-compressed data you are trying to decompress. Ensure the data source is reliable and that the entire compressed stream is received before attempting decompression. If fetching from a server, check server-side compression settings and content delivery.
Upgrade
Version history
1.2.0latest on PyPI · released Nov 5, 2025
Audit
Dependencies

No dependency data recorded yet.

Agent activity
30 hits · last 30 days
node
28
OpenAI (training)
1
Resources
brotli — pip install brotli · libregistry