[Python-Dev] dict.addlist()

Bob Ippolito bob at redivi.com
Tue Jan 20 13:50:43 EST 2004


On Jan 20, 2004, at 1:32 PM, Raymond Hettinger wrote:

> [GvR]
>>> bookindex = dict()
>>
>> (What's wrong with {}?)
>
> Nothing at all.  {} is shorter, faster, and everyone understands it.
>
> When teasing out ideas at the interpreter prompt, I tend to use
> dict() because I find it easier to edit the line and add some
> initial values using dict(one=1, two=2, s='abc').
>
>> works for me.  (I think setdefault() was already a minor mistake -- by
>> the time I've realized it applies I have already written working code
>> without it.  And when using setdefault() I always worry about the
>> waste of the new empty list passed in each time that's ignored most
>> times.)
>>
>> If you really want library support for this idiom ...
>
> Not really.  It was more of a time machine question -- if we had
> setdefault() to do over again, what would be done differently:
>
> * Keep setdefault().
> * Drop it and make do with get(), try/except, or if k in d.
> * Martin's idea for dicts to have an optional factory function for
> defaults.
> * Have a specialized method that just supports dicts of lists.

Here's another idea: how about adding a special method, similar in 
implementation to __getattr__, but for __getitem__ -- let's say it's 
called __getdefaultitem__?  You could then subclass dict, implement 
this method, and you'd probably be able to do what you want rather 
efficiently.  You may or may not decide to "cache" the value inside 
your custom __getdefaultitem__, and if you do, you may or may not want 
to change the behavior of __contains__ as well.

# warning: untested code
class newdict(dict):
	"""Implements the proposed protocol"""
	def __getitem__(self, item):
		try:
			return super(newdict, self).__getitem__(item)
		except KeyError:
			return self.__getdefaultitem__(item)

	def __getdefaultitem__(self, item):
		raise KeyError(repr(item))

class listdict(newdict):
	def __getdefaultitem__(self, item):
		self[item] = rval = []
		return rval

-bob




More information about the Python-Dev mailing list