Dbm.py :  » 3.1.2-Python » Demo » Demo » classes » Python Open Source

Home
Python Open Source
1.3.1.2 Python
2.Ajax
3.Aspect Oriented
4.Blog
5.Build
6.Business Application
7.Chart Report
8.Content Management Systems
9.Cryptographic
10.Database
11.Development
12.Editor
13.Email
14.ERP
15.Game 2D 3D
16.GIS
17.GUI
18.IDE
19.Installer
20.IRC
21.Issue Tracker
22.Language Interface
23.Log
24.Math
25.Media Sound Audio
26.Mobile
27.Network
28.Parser
29.PDF
30.Project Management
31.RSS
32.Search
33.Security
34.Template Engines
35.Test
36.UML
37.USB Serial
38.Web Frameworks
39.Web Server
40.Web Services
41.Web Unit
42.Wiki
43.Windows
44.XML
Python Open Source » 3.1.2 Python » Demo 
Demo » Demo » classes » Dbm.py
# A wrapper around the (optional) built-in class dbm, supporting keys
# and values of almost any type instead of just string.
# (Actually, this works only for keys and values that can be read back
# correctly after being converted to a string.)


class Dbm:

    def __init__(self, filename, mode, perm):
        import dbm.ndbm
        self.db = dbm.ndbm.open(filename, mode, perm)

    def __repr__(self):
        s = ''
        for key in self.keys():
            t = repr(key) + ': ' + repr(self[key])
            if s: t = ', ' + t
            s = s + t
        return '{' + s + '}'

    def __len__(self):
        return len(self.db)

    def __getitem__(self, key):
        return eval(self.db[repr(key)])

    def __setitem__(self, key, value):
        self.db[repr(key)] = repr(value)

    def __delitem__(self, key):
        del self.db[repr(key)]

    def keys(self):
        res = []
        for key in self.db.keys():
            res.append(eval(key))
        return res

    def has_key(self, key):
        return repr(key) in self.db


def test():
    d = Dbm('@dbm', 'rw', 0o600)
    print(d)
    while 1:
        try:
            key = eval(input('key: '))
            if key in d:
                value = d[key]
                print('currently:', value)
            value = eval(input('value: '))
            if value is None:
                del d[key]
            else:
                d[key] = value
        except KeyboardInterrupt:
            print('')
            print(d)
        except EOFError:
            print('[eof]')
            break
    print(d)


test()
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.