File: _dumb_shelve.py

package info (click to toggle)
python-scipy 0.18.1-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 75,464 kB
  • ctags: 79,406
  • sloc: python: 143,495; cpp: 89,357; fortran: 81,650; ansic: 79,778; makefile: 364; sh: 265
file content (51 lines) | stat: -rw-r--r-- 1,380 bytes parent folder | download | duplicates (2)
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
from __future__ import division, print_function, absolute_import

from shelve import Shelf
try:
    import zlib
except ImportError:
    # Some python installations don't have zlib.
    pass

import pickle


class DbfilenameShelf(Shelf):
    """Shelf implementation using the "anydbm" generic dbm interface.

    This is initialized with the filename for the dbm database.
    See the module's __doc__ string for an overview of the interface.
    """

    def __init__(self, filename, flag='c'):
        from . import _dumbdbm_patched
        Shelf.__init__(self, _dumbdbm_patched.open(filename, flag))

    def __getitem__(self, key):
        compressed = self.dict[key]
        try:
            r = zlib.decompress(compressed)
        except zlib.error:
            r = compressed
        except NameError:
            r = compressed

        return pickle.loads(r)

    def __setitem__(self, key, value):
        s = pickle.dumps(value,1)
        try:
            self.dict[key] = zlib.compress(s)
        except NameError:
            #zlib doesn't exist, leave it uncompressed.
            self.dict[key] = s


def open(filename, flag='c'):
    """Open a persistent dictionary for reading and writing.

    Argument is the filename for the dbm database.
    See the module's __doc__ string for an overview of the interface.
    """

    return DbfilenameShelf(filename, flag)