Skip to content

Commit 3e48e34

Browse files
committed
-
1 parent 1b41792 commit 3e48e34

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

python_toolbox/pickle_tools.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
'''Defines various tools for pickling and unpickling.'''
55

66

7+
import zlib
78
import re
89
import cPickle as pickle_module
910
import pickle # Importing just to get dispatch table, not pickling with it.
@@ -186,4 +187,8 @@ def persistent_load(self, id_string):
186187
raise pickle_module.UnpicklingError('Invalid persistent id')
187188

188189

189-
190+
def pickle_and_compress(thing):
191+
return zlib.compress(pickle_module.dumps(thing, protocol=2))
192+
193+
def decompress_and_unpickle(thing):
194+
return pickle_module.loads(zlib.decompress(thing))
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Copyright 2009-2013 Ram Rachum.
2+
# This program is distributed under the MIT license.
3+
4+
# We're importing `pickle_module` from `pickle_tools`, so we get the exact same
5+
# pickle module it's using. (Giving it the freedom to change between `cPickle`
6+
# and `pickle`.)
7+
from python_toolbox.pickle_tools import pickle_module
8+
9+
import nose
10+
11+
from python_toolbox import import_tools
12+
13+
from python_toolbox import pickle_tools
14+
15+
16+
my_messy_object = (
17+
'Whatever',
18+
{1: 2,},
19+
set([3, 4]),
20+
frozenset([3, 4]),
21+
((((((((((((())))))))))))),
22+
u'unicode_too',
23+
(((((3, 4, 5j)))))
24+
)
25+
26+
def test():
27+
pickled_and_compressed = pickle_tools.pickle_and_compress(my_messy_object)
28+
assert pickle_tools.decompress_and_unpickle(pickled_and_compressed) == \
29+
my_messy_object

0 commit comments

Comments
 (0)