zlib.
How It Works
zlib.decompress() restores bytes from a compatible zlib-compressed stream; corrupt data raises zlib.error. Untrusted compressed streams can expand enormously, so production decoders should cap resource use.
Step-by-Step Example
import zlib
original_bytes = b'archive metadata'
compressed_bytes = zlib.compress(original_bytes)
print(zlib.decompress(compressed_bytes) == original_bytes)
Understanding the Example
- The expression "b'archive metadata'" supplies the value stored as 'original_bytes'. This value is then used or checked by the later statements.
- The expression 'zlib.compress(original_bytes)' supplies the value stored as 'compressed_bytes'. This value is then used or checked by the later statements.
A successful run of this example prints the following output:
True
Where This Fits in a Real Program
A practical archive workflow has separate decisions for selection, compression, extraction and verification. When files come from other people, inspect paths, member counts and uncompressed sizes before writing anything; a successful decompression does not establish that its contents are trustworthy.
Practice: Try It Yourself
Corrupt one compressed stream and catch the error separately from a valid round trip.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Using zlib.decompress() on gzip data without matching wrapper settings or blindly decompressing unknown large data.
- The decompressed result is bytes; decode only when the payload is known to be text.
Key Takeaways
- zlib.
- zlib.decompress() restores bytes from a compatible zlib-compressed stream; corrupt data raises zlib.error.
- The decompressed result is bytes; decode only when the payload is known to be text.