forked from menpo/menpo
/
pickle.py
60 lines (50 loc) · 1.55 KB
/
pickle.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import sys
try:
import cPickle as pickle
except ImportError:
import pickle
import gzip
def _unpickle_with_encoding(f, encoding=None):
# Support the encoding kwarg on Python 3.x only.
if encoding is not None and sys.version_info.major > 2:
return pickle.load(f, encoding=encoding)
else:
return pickle.load(f)
def pickle_importer(filepath, asset=None, **kwargs):
r"""Import a pickle file.
Parameters
----------
filepath : `Path`
Absolute filepath of the file.
asset : `object`, optional
An optional asset that may help with loading. This is unused for this
implementation.
\**kwargs : `dict`, optional
Any other keyword arguments.
Returns
-------
object : `object`
The pickled objects.
"""
with open(str(filepath), 'rb') as f:
x = _unpickle_with_encoding(f, encoding=kwargs.get('encoding'))
return x
def pickle_gzip_importer(filepath, asset=None, **kwargs):
r"""Import a pickle file that has been compressed with GZip compression.
Parameters
----------
filepath : `Path`
Absolute filepath of the file.
asset : `object`, optional
An optional asset that may help with loading. This is unused for this
implementation.
\**kwargs : `dict`, optional
Any other keyword arguments.
Returns
-------
object : `object`
The pickled objects.
"""
with gzip.open(str(filepath), 'rb') as f:
x = _unpickle_with_encoding(f, encoding=kwargs.get('encoding'))
return x