1
2
3
4
5
6
7
8
9 """Helper for simple storage facility via cPickle and zlib"""
10
11 __docformat__ = 'restructuredtext'
12
13 import os
14
15 from mvpa.base import externals
16 externals.exists('cPickle', raiseException=True)
17 externals.exists('gzip', raiseException=True)
18
19 _d_geti_ = dict.__getitem__
20 _d_seti_ = dict.__setitem__
21
22 _o_geta_ = dict.__getattribute__
23 _o_seta_ = dict.__setattr__
24
25 import cPickle, gzip
26
27 if __debug__:
28 from mvpa.base import debug
29
31 """Simple container class which is derived from the dictionary
32
33 It is capable of storing itself in a file, or loading from a file
34 (using cPickle + zlib tandem). Any serializable object can be
35 bound to a hamster to be stored.
36
37 To undig burried hamster use Hamster(filename). Here is an example:
38
39 >>> h = Hamster(bla='blai')
40 >>> h.boo = N.arange(5)
41 >>> h.dump(filename)
42 ...
43 >>> h = Hamster(filename)
44 """
45
47 if len(args) == 1 and isinstance(args[0], basestring):
48 filename = args[0]
49 args = args[1:]
50 if __debug__:
51 debug('IOH', 'Undigging hamster from %s' % filename)
52 f = gzip.open(filename)
53 result = cPickle.load(f)
54 if not isinstance(result, Hamster):
55 warning("Loaded other than Hamster class from %s" % filename)
56 return result
57 else:
58 return dict.__new__(cls, *args, **kwargs)
59
60
62 """Initialize Hamster.
63
64 Providing a single parameter string would treat it as a
65 filename from which to undig the data. Otherwise all the
66 parameters are equivalent to the ones of dict
67 """
68 if len(args) == 1 and isinstance(args[0], basestring):
69
70 args = args[1:]
71 dict.__init__(self, *args, **kwargs)
72
73
74 - def dump(self, filename):
75 """Bury the hamster into the file
76 """
77 if __debug__:
78 debug('IOH', 'Burying hamster into %s' % filename)
79 f = gzip.open(filename, 'w')
80 cPickle.dump(self, f)
81 f.close()
82
83
94
95
103