[Python-checkins] r69267 - sandbox/trunk/dbm_sqlite/alt/dbdict.py
raymond.hettinger
python-checkins at python.org
Wed Feb 4 09:56:31 CET 2009
Author: raymond.hettinger
Date: Wed Feb 4 09:56:31 2009
New Revision: 69267
Log:
Move dump/load inside the class definition.
Modified:
sandbox/trunk/dbm_sqlite/alt/dbdict.py
Modified: sandbox/trunk/dbm_sqlite/alt/dbdict.py
==============================================================================
--- sandbox/trunk/dbm_sqlite/alt/dbdict.py (original)
+++ sandbox/trunk/dbm_sqlite/alt/dbdict.py Wed Feb 4 09:56:31 2009
@@ -14,15 +14,16 @@
class DictDB(dict):
- def __init__(self, filename, flag='c', mode=None, *args, **kwds):
+ def __init__(self, filename, flag='c', mode=None, format='csv', *args, **kwds):
# r=readonly c=read_write_create_if_needed n=new_overwrite_previous
self.flag = flag
self.mode = mode
- self.filename = filename
+ self.format = format
+ self.filename = filename
if flag != 'n' and os.access(filename, os.R_OK):
file = __builtins__.open(filename, 'rb')
try:
- self.update(load(file))
+ self.update(self.load(file))
finally:
file.close()
self.update(*args, **kwds)
@@ -31,7 +32,7 @@
if self.flag != 'r':
file = __builtins__.open(self.filename, 'wb')
try:
- dump(self, file)
+ self.dump(file)
finally:
file.close()
if self.mode:
@@ -40,35 +41,36 @@
def close(self):
self.sync()
-def myopen(filename, flag='c', mode=0o666):
- return DictDB(filename, flag, mode)
-
-def set_csv():
- global load, dump
- def load(f):
- ans = list(csv.reader(f))
- return ans
def dump(self, f):
- csv.writer(f).writerows(self.items())
+ if self.format == 'csv':
+ csv.writer(f).writerows(self.iteritems())
+ elif self.format == 'json':
+ json.dump(self, f, separators=(',',':'))
+ elif self.format == 'pickle':
+ pickle.dump(self.items(), f, -1)
+ else:
+ raise NotImplementedError('Unknown format: %r' % self.format)
+
+ def load(self, f):
+ if self.format == 'csv':
+ return csv.reader(f)
+ elif self.format == 'json':
+ return json.load(f)
+ elif self.format == 'pickle':
+ return pickle.load(f)
+ else:
+ raise NotImplementedError('Unknown format: %r' % self.format)
+
+
+def myopen(filename, flag='c', mode=0o666, format='csv'):
+ return DictDB(filename, flag, mode, format)
-def set_json():
- global load, dump
- load = json.load
- def dump(self, f):
- json.dump(self, f, separators=(',',':'))
-def set_pickle():
- global load, dump
- load = pickle.load
- def dump(self, f):
- pickle.dump(self, f, -1)
-
-set_csv()
if __name__ == '__main__':
os.chdir('/dbm_sqlite/alt')
print(os.getcwd())
- s = myopen('tmp.shl', 'c')
+ s = myopen('tmp.shl', 'c', format='json')
print(s, 'start')
s['xyz'] = 'pdq'
s['abc'] = '123'
More information about the Python-checkins
mailing list