summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
authorAntoine Pitrou <solipsis@pitrou.net>2010-08-17 21:10:05 (GMT)
committerAntoine Pitrou <solipsis@pitrou.net>2010-08-17 21:10:05 (GMT)
commit79c5ef11d56e761445e334a7121764808e9e70cf (patch)
tree529b00a3e891a4c14b4c5e1ac6971f490ba62784 /Lib
parent852823d731a6370c078016f3825044eec74fbb4f (diff)
downloadcpython-79c5ef11d56e761445e334a7121764808e9e70cf.zip
cpython-79c5ef11d56e761445e334a7121764808e9e70cf.tar.gz
cpython-79c5ef11d56e761445e334a7121764808e9e70cf.tar.bz2
Issue #3488: Provide convenient shorthand functions `gzip.compress`
and `gzip.decompress`. Original patch by Anand B. Pillai.
Diffstat (limited to 'Lib')
-rw-r--r--Lib/gzip.py19
-rw-r--r--Lib/test/test_gzip.py20
2 files changed, 38 insertions, 1 deletions
diff --git a/Lib/gzip.py b/Lib/gzip.py
index fab55a3..83311cc 100644
--- a/Lib/gzip.py
+++ b/Lib/gzip.py
@@ -10,7 +10,7 @@ import zlib
import builtins
import io
-__all__ = ["GzipFile","open"]
+__all__ = ["GzipFile", "open", "compress", "decompress"]
FTEXT, FHCRC, FEXTRA, FNAME, FCOMMENT = 1, 2, 4, 8, 16
@@ -476,6 +476,23 @@ class GzipFile(io.BufferedIOBase):
return b''.join(bufs) # Return resulting line
+def compress(data, compresslevel=9):
+ """Compress data in one shot and return the compressed string.
+ Optional argument is the compression level, in range of 1-9.
+ """
+ buf = io.BytesIO()
+ with GzipFile(fileobj=buf, mode='wb', compresslevel=compresslevel) as f:
+ f.write(data)
+ return buf.getvalue()
+
+def decompress(data):
+ """Decompress a gzip compressed string in one shot.
+ Return the decompressed string.
+ """
+ with GzipFile(fileobj=io.BytesIO(data)) as f:
+ return f.read()
+
+
def _test():
# Act like gzip; with -d, act like gunzip.
# The input file is not deleted, however, nor are any other gzip
diff --git a/Lib/test/test_gzip.py b/Lib/test/test_gzip.py
index 7eade6f..a95af05 100644
--- a/Lib/test/test_gzip.py
+++ b/Lib/test/test_gzip.py
@@ -265,6 +265,26 @@ class TestGzip(unittest.TestCase):
d = f.read()
self.assertEqual(d, data1 * 50, "Incorrect data in file")
+ # Testing compress/decompress shortcut functions
+
+ def test_compress(self):
+ for data in [data1, data2]:
+ for args in [(), (1,), (6,), (9,)]:
+ datac = gzip.compress(data, *args)
+ self.assertEqual(type(datac), bytes)
+ with gzip.GzipFile(fileobj=io.BytesIO(datac), mode="rb") as f:
+ self.assertEqual(f.read(), data)
+
+ def test_decompress(self):
+ for data in (data1, data2):
+ buf = io.BytesIO()
+ with gzip.GzipFile(fileobj=buf, mode="wb") as f:
+ f.write(data)
+ self.assertEqual(gzip.decompress(buf.getvalue()), data)
+ # Roundtrip with compress
+ datac = gzip.compress(data)
+ self.assertEqual(gzip.decompress(datac), data)
+
def test_main(verbose=None):
support.run_unittest(TestGzip)