Python Glossary Русский

Python 3.14+compression.zstdfunction

compression.zstd.compress()

in-memory compression

Compresses bytes with Zstandard in one call and returns a complete zstd frame. Levels range from negative (fast) to 22 (dense).

Syntax

compression.zstd.compress(data, level=None, options=None, zstd_dict=None)

level and options are mutually exclusive: passing both raises TypeError, so set the level through CompressionParameter.compression_level inside options instead. A level outside the valid range raises ValueError that names the range; the default is 3. Negative levels mean faster than any gzip, not an error. Input must be bytes-like: encode a str with .encode() first.

Examples

# Python 3.14+
from compression import zstd  # → ? нужна сборка CPython с libzstd
data = 'строка лога\n'.encode() * 200
packed = zstd.compress(data, level=10)
print(len(packed) < len(data), packed[:4])  # → True b'(\xb5/\xfd' — магия кадра zstd
print(zstd.decompress(packed) == data)  # → True
# Python 3.14+
from compression import zstd  # → ? нужна сборка CPython с libzstd
try:
    zstd.compress(b'x', level=3, options={zstd.CompressionParameter.checksum_flag: 1})
except TypeError as e:
    print(e)  # → Only one of level or options should be used.
try:
    zstd.compress(b'x', level=100)
except ValueError as e:
    print('ValueError')  # → ValueError

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy