~ubuntu-branches/ubuntu/karmic/python-scipy/karmic

« back to all changes in this revision

Viewing changes to Lib/io/dumb_shelve.py

  • Committer: Bazaar Package Importer
  • Author(s): Daniel T. Chen (new)
  • Date: 2005-03-16 02:15:29 UTC
  • Revision ID: james.westby@ubuntu.com-20050316021529-xrjlowsejs0cijig
Tags: upstream-0.3.2
ImportĀ upstreamĀ versionĀ 0.3.2

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
from shelve import Shelf
 
2
try:
 
3
    import zlib
 
4
except ImportError:
 
5
    # Some python installations don't have zlib.
 
6
    pass    
 
7
    
 
8
from cStringIO import  StringIO
 
9
import  cPickle  
 
10
 
 
11
class DbfilenameShelf(Shelf):
 
12
    """Shelf implementation using the "anydbm" generic dbm interface.
 
13
 
 
14
    This is initialized with the filename for the dbm database.
 
15
    See the module's __doc__ string for an overview of the interface.
 
16
    """
 
17
    
 
18
    def __init__(self, filename, flag='c'):
 
19
        import dumbdbm_patched
 
20
        Shelf.__init__(self, dumbdbm_patched.open(filename, flag))
 
21
 
 
22
    def __getitem__(self, key):
 
23
        compressed = self.dict[key]
 
24
        try:
 
25
            r = zlib.decompress(compressed)
 
26
        except zlib.error:
 
27
            r = compressed
 
28
        except NameError:
 
29
            r = compressed    
 
30
            
 
31
        return cPickle.loads(r) 
 
32
        
 
33
    def __setitem__(self, key, value):
 
34
        s = cPickle.dumps(value,1)
 
35
        try:
 
36
            self.dict[key] = zlib.compress(s)
 
37
        except NameError:
 
38
            #zlib doesn't exist, leave it uncompressed.
 
39
            self.dict[key] = s
 
40
 
 
41
def open(filename, flag='c'):
 
42
    """Open a persistent dictionary for reading and writing.
 
43
 
 
44
    Argument is the filename for the dbm database.
 
45
    See the module's __doc__ string for an overview of the interface.
 
46
    """
 
47
    
 
48
    return DbfilenameShelf(filename, flag)