%
Fredrik Lundh
fredrik at pythonware.com
Sat May 1 06:43:10 EDT 1999
Phil Hunt <philh at vision25.demon.co.uk> wrote:
> Consider the % operator, eg:
>
> 'All %(a)s eat %(b)s' % {'a':'cows', 'b':'grass'}
>
> If the dictionary doesn't have all the relevant keys, an error
> occurs. Is it possible for me to change the behaviour of this so that
> if a key doesn't occur a default value of '' is assumed?
class D:
def __init__(self, dict=None, **extra):
self.dict = dict or {}
self.dict.update(extra)
def __getitem__(self, key):
try:
return self.dict[key]
except KeyError:
return ""
print 'All %(a)s eat %(b)s' % {'a': 'cows', 'b': 'grass'}
print 'All %(a)s eat %(b)s' % D({'c': 'swines', 'b': 'pearls'})
print 'All %(a)s eat %(b)s' % D(a='pythoneers', b='spam')
</F>
More information about the Python-list
mailing list