On this page
  1. zlib
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Bounded Streaming Decompression (decompressobj + max_length)
  7. 2. Raw DEFLATE vs. Gzip Framing (wbits)
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects
  11. Constants & Attributes

zlib

Prev: zipimport | Up: stdlib_module | Next: zoneinfo
Rel: pickle, copyreg, shelve, marshal, dbm
Ref: docs.python.org — zlib
Tags: #public #python3 #stdlib


Import

import zlib

Overview

Low-level bindings to the C zlib DEFLATE compression library (compress, decompress, compressobj, decompressobj, crc32, adler32). Reach for zlib for raw in-memory or streaming DEFLATE payloads (HTTP Content-Encoding, Git loose objects, PNG chunks); use gzip when you need standard .gz files.

Quick Start

import zlib

raw = b"compress this repeated payload " * 50
compressed = zlib.compress(raw, level=6)
assert len(compressed) < len(raw)
assert zlib.decompress(compressed) == raw
assert zlib.crc32(raw) & 0xFFFFFFFF >= 0

Implementation Walkthrough

1. Bounded Streaming Decompression (decompressobj + max_length)

Always pass max_length= when decompressing untrusted data so a tiny 10 KB zip bomb cannot expand into gigabytes of RAM:

import zlib

def safe_decompress(data: bytes, *, max_bytes: int = 1_000_000) -> bytes:
    decomp = zlib.decompressobj()
    out = decomp.decompress(data, max_bytes + 1)
    if len(out) > max_bytes or decomp.unconsumed_tail:
        raise ValueError("Decompressed output exceeded max_bytes")
    out += decomp.flush()
    if len(out) > max_bytes:
        raise ValueError("Decompressed output exceeded max_bytes")
    return out

blob = zlib.compress(b"hello" * 10)
assert safe_decompress(blob, max_bytes=100) == b"hello" * 10

2. Raw DEFLATE vs. Gzip Framing (wbits)

wbits=15 (default) uses zlib headers; wbits=-15 is raw DEFLATE (no header); wbits=16 + 15 handles gzip framing.

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes