[Web-SIG] htmlgen
Gregory (Grisha) Trubetskoy
grisha at modpython.org
Thu Oct 30 14:09:29 EST 2003
On Thu, 30 Oct 2003, Ian Bicking wrote:
> This would solve this particular problem:
>
> class EmptyStringDict(dict):
> def __getitem__(self, item):
> try:
> return dict.__getitem__(self, item)
> except KeyError:
> return ''
Neat trick! Here is an even more generic version:
class DefaultDict(dict):
def __init__(self, init={}, default=""):
self.default = default
dict.__init__(self, init)
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
return self.default
Now I can do:
>>> "Hello %(title)s %(name)s, how are you?" % DefaultDict({'title' : 'Mr.', 'name' : 'Smith'})
'Hello Mr. Smith, how are you?'
>>>
>>> "Hello %(title)s %(name)s, how are you?" % DefaultDict({'name' : 'Smith'})
'Hello Smith, how are you?'
>>>
Grisha
More information about the Web-SIG
mailing list