Compare Bzip2 and LZMA Interfaces
Core idea
The bz2 and lzma modules have parallel one-shot compress and decompress functions and file-like BZ2File and LZMAFile interfaces. Select the format required by the receiver; the algorithms are not interchangeable. LZMA defaults to an XZ container for compression. Compression ratio and CPU cost depend on input and settings.
import bz2, lzmaraw = b"row:5\n" * 40for codec in (bz2, lzma): print(codec.__name__, codec.decompress(codec.compress(raw)) == raw)Each decoder restores the data produced by its own encoder.
Use an XZ stream
import lzmafrom io import BytesIOwith lzma.LZMAFile(BytesIO(lzma.compress(b"ABCD")), "rb") as f: print(f.read(2), f.read(2))Read sizes refer to decompressed bytes.
Common mistake
Do not assume the smallest result for one fixture predicts performance for all inputs. Optional native compression modules may be missing in some builds.
Practice
Compare round-trip equality and compressed lengths for a repeated byte sequence and a short mixed sequence, without asserting a universal winner.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Compression formats
Check your understanding of bzip2 and lzma.
What is printed?
import bz2print(bz2.decompress(bz2.compress(b"xy")) == b"xy")What is printed?
import lzmaprint(len(lzma.decompress(lzma.compress(b"abc"))))Which container does lzma.compress use by default?
What is required to compare compression performance?