On this page
compression
Prev: compileall | Up: stdlib_module | Next: concurrent
Rel: pickle, copyreg, shelve, marshal, dbm
Ref: docs.python.org — compression
Tags: #public #python3 #stdlib
Import
import compression
Overview
Python 3.14+ unified compression namespace (compression.zstd, compression.gzip, compression.bz2, compression.lzma, compression.zlib)—most notably adding Zstandard (compression.zstd) directly into the standard library (PEP 784) for fast, high-ratio compression with zero third-party packages.
Quick Start
from compression import zstd
raw = b"fast modern zstandard compression " * 100
compressed = zstd.compress(raw)
assert len(compressed) < len(raw)
assert zstd.decompress(compressed) == raw
Implementation Walkthrough
1. Streaming .zst Files with compression.zstd.open()
from compression import zstd
from pathlib import Path
import tempfile
with tempfile.TemporaryDirectory() as tmp:
p = Path(tmp) / "log.txt.zst"
with zstd.open(p, "wt", encoding="utf-8") as fh:
fh.write("line 1\nline 2\n")
with zstd.open(p, "rt", encoding="utf-8") as fh:
assert fh.read() == "line 1\nline 2\n"
Gotchas & Boundaries
- Python 3.14+ only: Earlier Python versions use top-level
gzip,bz2,lzma, andzlib(and have no stdlibzstd). - Prefer
compression.zstdovergzip/bz2for new Python 3.14+ formats: Zstandard delivers faster compression and decompression with better ratios than gzip. - Bound decompression sizes on untrusted input using streaming
ZstdDecompressorreads to guard against compression bombs.
Linked from
Related notes
- tuts/python3/stdlib_module/compileall Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/concurrent Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/copyreg Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/dbm Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/marshal Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/pickle Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/shelve Linked here; shared tags: #stdlib
- tuts/c/stdlib shared tags: #stdlib