[Python-Dev] defaultdict proposal round three

Guido van Rossum guido at python.org
Tue Feb 21 00:23:36 CET 2006


On 2/20/06, Dan Gass <dan.gass at gmail.com> wrote:
> Why not have the factory function take the key being looked up as an
> argument?

This was considered and rejected already.

You can already customize based on the key by overriding on_missing()
[*]. If the factory were to take a key argument, we couldn't use list
or int as the factory function; we'd have to write lambda key: list().
There aren't that many use cases for having the factory function
depend on the key anyway; it's mostly on_missing() that needs the key
so it can insert the new value into the dict.

[*] Earlier in this thread I wrote that on_missing() could be inlined.
I take that back; I think it's better to have it be available
explicitly so you can override it without having to override
__getitem__(). This is faster, assuming most __getitem__() calls find
the key already inserted, and reduces the amount of code you have to
write to customize the behavior; it also reduces worries about how to
call the superclass __getitem__ method (catching KeyError *might*
catch an unrelated KeyError caused by a bug in the key's __hash__ or
__eq__ method).

--
--Guido van Rossum (home page: http://www.python.org/~guido/)


More information about the Python-Dev mailing list