Welcome, guest | Sign In | My Account | Store | Cart

Enables objects to be stored as values in an anydbm file.

Python, 51 lines
 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
import anydbm
import marshal

class marshaldbm(object):
    """
    Incorporating marshalling capabilities into anydbm module to store
    marshallable objects as values. The keys and values in anydbm must be
    strings. Marshalling capability is added for the values.
    
    >>> d = open('test.db', 'c')
    >>> d['a list'] = ['a', 'b']
    >>> d.close()
    """
    def __init__(self, dbfile, flag):
        """
        Constructor method - opens database file or creates new database file.
        @param dbfile: path of database file
        @param flag: file opening mode for anydbm
        """
        self.dbfile = anydbm.open(dbfile, flag)

    def __setitem__(self, key, item):
        """
        Method to put items into the database file.
        """
        item = marshal.dumps(item)
        self.dbfile[key] = item

    def __getitem__(self, key):
        """
        Method to get items from the databasde file using its key
        """
        return marshal.loads(self.dbfile[key])

    def __len__(self):
        """
        Returns the row count of the database file
        """
        return len(self.dbfile)

    def close(self):
        """
        Closes the database file
        """
        self.dbfile.close()

    def keys(self):
        """
        Returns a list of keys in the database file
        """
        return [key for key in self.dbfile.keys()]

1 comment

Gabriel Genellina 14 years, 3 months ago  # | flag

So this is like the shelve module, but using marshal instead of pickle.

There is a problem with the marshal format: it's not guaranteed to remain compatible across Python versions, so after upgrading Python, you may find that you can't read your data anymore. Pickles are documented to be compatible.

Also, marshal is quite limited, it can only understand basic built-in types, you can't marshal instances of any user-defined type nor complex structures.

Of course, if one is aware of its limitations, this recipe may be rather useful.