Entry
"Safe" dictionary
Oct 26th, 2006 04:21
alex novo, Nathan Wallace, unknown unknown, Hans Nowak, Snippet 345, Barry A. Warsaw
"""
Packages: basic_datatypes.dictionaries
"""
"""
GH> This is ugly! Isn't there a better way to fill in just SOME of
GH> the %(...)s values in a string and leave the rest as is?
Here's what we use in Mailman:
"""
from UserDict import UserDict # added by PSST
class SafeDict(UserDict):
"""Dictionary which returns a default value for unknown keys.
"""
def __init__(self, d=None):
# optional initial dictionary is a Python 1.5.2-ism. Do it
this way
# for portability
UserDict.__init__(self)
if d:
self.update(d)
def __getitem__(self, key):
try:
return self.data[key]
except KeyError:
if type(key) == StringType:
return '%('+key+')s'
else:
return '<Missing key: %s>' % `key`