ideasman42
ideasman42

Reputation: 48218

How to set compression level while using `zipfile` with LZMA compression?

Documention for zipfile notes that the compresslevel argument does nothing for when LZMA compression is used. So how can the LZMA compression level be set for ZIP files created with Python. See: https://docs.python.org/3/library/zipfile.html


See: related question for tarfile
How to set compression level while using `tarfile` with LZMA compression?

Upvotes: 0

Views: 78

Answers (1)

ideasman42
ideasman42

Reputation: 48218

The short answer to this question is:

As of Python 3.12 this is not supported using the official API's.


This can actually be done by monkey-patching an internal function, but this could break in future Python releases so it's far from ideal.

Further, internally this uses RAW LZMA1 encoding, so internally the LZMA doesn't provide presets, instead there are many tunable options what can be configured. This example shows how the dictionary size can be set to 64mb (which is used for the preset=9), although I didn't check on all the other settings.

def lzma_use_max_compress()
    def encode_filter_properties_wrapper(filter_orig):
        filter_copy = {**filter_orig}
        if "dict_size" not in filter_copy:
            filter_copy["dict_size"] = 67108864
        return encode_filter_properties_wrapper.fn(filter_copy)


    encode_filter_properties_wrapper.fn = lzma._encode_filter_properties
    lzma._encode_filter_properties = encode_filter_properties_wrapper

After lzma_use_max_compress runs, the dictionary size for LZMA compressed zipfiles will be 64mb.

Upvotes: 0

Related Questions