thread merge
[mailman.git] / mailman / SafeDict.py
blob1549777daaed6c867e7d26151d5d36592bab0a1c
1 # Copyright (C) 1998-2008 by the Free Software Foundation, Inc.
3 # This program is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU General Public License
5 # as published by the Free Software Foundation; either version 2
6 # of the License, or (at your option) any later version.
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software
15 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
16 # USA.
18 from mailman.configuration import config
20 """A `safe' dictionary for string interpolation."""
22 COMMASPACE = ', '
24 # XXX This module should go away.
28 class SafeDict(dict):
29 """Dictionary which returns a default value for unknown keys.
31 This is used in maketext so that editing templates is a bit more robust.
32 """
33 def __init__(self, d='', charset=None, lang=None):
34 super(SafeDict, self).__init__(d)
35 if charset:
36 self.cset = charset
37 elif lang:
38 self.cset = config.languages.get_charset(lang)
39 else:
40 self.cset = 'us-ascii'
42 def __getitem__(self, key):
43 try:
44 return super(SafeDict, self).__getitem__(key)
45 except KeyError:
46 if isinstance(key, basestring):
47 return '%('+key+')s'
48 else:
49 return '<Missing key: %s>' % `key`
51 def interpolate(self, template):
52 for k, v in self.items():
53 if isinstance(v, str):
54 self.__setitem__(k, unicode(v, self.cset))
55 return template % self