Bound Decompressed Stream Consumption
Core idea
Read compressed streams in bounded chunks instead of materializing an entire output. Maintain a cumulative byte count and abort when the budget is exceeded. A small read size limits the bytes returned by that call, not the total work or internal decoder allocation.
import gzipfrom io import BytesIOwith gzip.GzipFile(fileobj=BytesIO(gzip.compress(b"abcdef")), mode="rb") as f: total = 0 while chunk := f.read(2): total += len(chunk) print(total)Each returned chunk contributes to the total; empty bytes indicate EOF. The assignment expression binds the chunk before testing it.
Stop after a small budget
import gzipfrom io import BytesIOwith gzip.GzipFile(fileobj=BytesIO(gzip.compress(b"abcdef")), mode="rb") as f: remaining = 4 while remaining >= 0: chunk = f.read(min(2, remaining + 1)) if not chunk: print("accepted") break remaining -= len(chunk) else: print("too large")At most one extra returned byte is needed to distinguish an exact limit from excess output. No output is persisted.
Common mistake
Do not equate this example with a complete archive security sandbox. Limit input, output, member count, CPU, memory and disk usage; do not commit partially validated output.
Practice
Repeat the second example with a four-byte and a three-byte fixture; verify both are accepted, then try five bytes.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Bounded consumption
Check your understanding of streaming archive processing.
What is printed?
import gzipfrom io import BytesIOwith gzip.GzipFile(fileobj=BytesIO(gzip.compress(b"123"))) as f: print(len(f.read(2)),len(f.read(2)))What is printed?
import gzipfrom io import BytesIOwith gzip.GzipFile(fileobj=BytesIO(gzip.compress(b"x"))) as f: f.read(1) print(f.read(1) == b"")Why maintain a cumulative counter?
Does a read size guarantee a CPU and memory bound?