Python Forum
compresslevel vs. preset - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: News and Discussions (https://python-forum.io/forum-31.html)
+--- Thread: compresslevel vs. preset (/thread-31060.html)



compresslevel vs. preset - Skaperen - Nov-20-2020

gzip.open() and bz2.open() both have a keyword argument compresslevel= to set the compression level while lzma.open() uses preset= for that. i am creating a function that selects one of these 3 to cal;. which keyword argument name should it use for compress level? the intent is for the caller to not need to know which algorithm is being used.


RE: compresslevel vs. preset - DeaD_EyE - Nov-20-2020

Name it compresslevel.

import bz2, gzip, lzma
import os


def open_compressed(file, mode, compresslevel=3):
    ext = os.path.splitext(file)[1]
    if ext == ".gz":
        return gzip.open(file, mode, compresslevel=compresslevel)
    elif ext == ".bz2":
        return bz2.open(file, mode, compresslevel=compresslevel)
    elif ext == ".xy":
        if mode == "r":
            return lzma.open(file, mode)
        else:
            return lzma.open(file, mode, preset=compresslevel)

testfiles = ("test.gz", "test.bz2", "test.xy")
# making testfiles
for file in testfiles:
    with open_compressed(file, "w", compresslevel=9) as fd:
        fd.write(file.upper().encode())

# reading
for file in testfiles:
    with open_compressed(file, "r") as fd:
        print(f"File: {file}: {fd.read().decode()}")
This is one of the design patterns, but I can't recognize the name.


RE: compresslevel vs. preset - Skaperen - Nov-21-2020

design patterns have names? ok, i'll use compresslevel= on my zopen() function.