Working with compressed data is a common task in Python, whether you're reducing storage size, speeding up network transfers, or handling large datasets efficiently. Traditionally, developers imported compression tools directly from modules like bz2, gzip, lzma, or zlib.
Since Python 3.14, there's a cleaner and more unified approach. A new top-level compression package groups the standard compression modules under a single namespace, making imports more consistent and future-proof.
The compression package re-exports existing modules:
compression.bz2compression.gzipcompression.lzmacompression.zlib
While the original module names still work, the new imports are the recommended choice going forward, as the old ones are expected to be deprecated in future Python releases.
Before Python 3.14, we would typically write code like this:
import bz2
import gzip
import lzma
import zlib
data = 'Hello world'
data_compressed = bz2.compress(data.encode())
data_restored = bz2.decompress(data_compressed).decode()
print(data_restored) # Hello world
data_compressed = gzip.compress(data.encode())
data_restored = gzip.decompress(data_compressed).decode()
print(data_restored) # Hello world
data_compressed = lzma.compress(data.encode())
data_restored = lzma.decompress(data_compressed).decode()
print(data_restored) # Hello world
data_compressed = zlib.compress(data.encode())
data_restored = zlib.decompress(data_compressed).decode()
print(data_restored) # Hello world
Since Python 3.14, the same functionality is available through the compression package:
from compression import bz2
from compression import gzip
from compression import lzma
from compression import zlib
data = 'Hello world'
data_compressed = bz2.compress(data.encode())
data_restored = bz2.decompress(data_compressed).decode()
print(data_restored) # Hello world
data_compressed = gzip.compress(data.encode())
data_restored = gzip.decompress(data_compressed).decode()
print(data_restored) # Hello world
data_compressed = lzma.compress(data.encode())
data_restored = lzma.decompress(data_compressed).decode()
print(data_restored) # Hello world
data_compressed = zlib.compress(data.encode())
data_restored = zlib.decompress(data_compressed).decode()
print(data_restored) # Hello world
The API remains unchanged - only the import path is different. This makes migrating existing code straightforward while aligning with the direction of the standard library.
Leave a Comment
Cancel reply