WriteableDict.py

#!/usr/bin/env python

"""
$Id: WriteableDict.py 277 2001-11-05 13:51:05Z david $

This module provides the WriteableDict class, which makes it
possible to write out a dictionary in valid Python syntax.
"""

from UserDict import UserDict


class WriteableDict (UserDict):
	def __init__ (self, other=None):
		UserDict.__init__(self)
		if type(other) == type({}):
			self.data = other.copy()
		elif isinstance(other, UserDict):
			self.data = other.data.copy()

	def write (self, filename, dictname="data"):
		if not filename[-3:] == ".py":
			filename = filename + ".py"
		f = open(filename, "w")
		f.write("# %s generated by WriteableDict.py\n" % filename)
		f.write("%s = {\n" % dictname)
		for key in self.data.keys():
			f.write("\t%s: %s,\n" % (repr(key),
			                         repr(self.data[key])))
		f.write("}\n")
		f.close()