Mercurial > cpython-lru_cache-weakref
annotate Demo/classes/Dbm.py @ 4566:6403c94de50d legacy-trunk
Added safeguard against failure in __del__.
| author | Guido van Rossum <guido@python.org> |
|---|---|
| date | Wed, 27 Nov 1996 19:39:58 +0000 |
| parents | 8701b93383ab |
| children | 558689b6d7f0 |
| rev | line source |
|---|---|
| 945 | 1 # A wrapper around the (optional) built-in class dbm, supporting keys |
| 2 # and values of almost any type instead of just string. | |
| 3 # (Actually, this works only for keys and values that can be read back | |
| 4 # correctly after being converted to a string.) | |
| 5 | |
| 6 | |
| 7 class Dbm: | |
| 8 | |
|
1377
3543ce88a31e
Fix bug and use __init__
Guido van Rossum <guido@python.org>
parents:
945
diff
changeset
|
9 def __init__(self, filename, mode, perm): |
| 945 | 10 import dbm |
| 11 self.db = dbm.open(filename, mode, perm) | |
| 12 | |
| 13 def __repr__(self): | |
| 14 s = '' | |
| 15 for key in self.keys(): | |
| 16 t = `key` + ': ' + `self[key]` | |
|
1377
3543ce88a31e
Fix bug and use __init__
Guido van Rossum <guido@python.org>
parents:
945
diff
changeset
|
17 if s: t = ', ' + t |
| 945 | 18 s = s + t |
| 19 return '{' + s + '}' | |
| 20 | |
| 21 def __len__(self): | |
| 22 return len(self.db) | |
| 23 | |
| 24 def __getitem__(self, key): | |
| 25 return eval(self.db[`key`]) | |
| 26 | |
| 27 def __setitem__(self, key, value): | |
| 28 self.db[`key`] = `value` | |
| 29 | |
| 30 def __delitem__(self, key): | |
| 31 del self.db[`key`] | |
| 32 | |
| 33 def keys(self): | |
| 34 res = [] | |
| 35 for key in self.db.keys(): | |
| 36 res.append(eval(key)) | |
| 37 return res | |
| 38 | |
| 39 def has_key(self, key): | |
| 40 return self.db.has_key(`key`) | |
| 41 | |
| 42 | |
| 43 def test(): | |
|
1427
8701b93383ab
*** empty log message ***
Guido van Rossum <guido@python.org>
parents:
1377
diff
changeset
|
44 d = Dbm('@dbm', 'rw', 0600) |
| 945 | 45 print d |
| 46 while 1: | |
| 47 try: | |
|
1427
8701b93383ab
*** empty log message ***
Guido van Rossum <guido@python.org>
parents:
1377
diff
changeset
|
48 key = input('key: ') |
| 945 | 49 if d.has_key(key): |
| 50 value = d[key] | |
| 51 print 'currently:', value | |
|
1377
3543ce88a31e
Fix bug and use __init__
Guido van Rossum <guido@python.org>
parents:
945
diff
changeset
|
52 value = input('value: ') |
| 945 | 53 if value == None: |
| 54 del d[key] | |
| 55 else: | |
| 56 d[key] = value | |
| 57 except KeyboardInterrupt: | |
| 58 print '' | |
| 59 print d | |
| 60 except EOFError: | |
| 61 print '[eof]' | |
| 62 break | |
| 63 print d | |
| 64 | |
| 65 | |
| 66 test() |
