Create dict key only when needed

Duncan Booth duncan at NOSPAMrcp.co.uk
Thu Feb 13 11:29:11 EST 2003


Helge Stenstrom <helge.stenstrom.NO at SPAM.ericsson.com> wrote in 
news:uel6ci8tm.fsf at SPAM.ericsson.com:

> How can the += syntax be used instead of calling a function?
> 
Here is one way:

>>> class DictWithDefault(dict):
	__slots__ = ['default']
	def __getitem__(self, name):
		try:
			return dict.__getitem__(self, name)
		except KeyError:
			return self.default

		
>>> a = DictWithDefault()
>>> a.default = ""
>>> a[17] += "foo"
>>> a[4711] += "foo"
>>> a[4711] += "bar"
>>> a
{17: 'foo', 4711: 'foobar'}
>>>

You would need a bit more code though if the default was to be a mutable 
such as a list.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list