[Python-3000] Default factory that uses key

Georg Brandl g.brandl at gmx.net
Sun Jan 6 11:07:40 CET 2008


hashcollision schrieb:
> The default factory that collections.defaultdict takes cannot use key. 
> Is there a way to have the default factory take the key into 
> consideration? For example
>  
> d = collections.defaultdict(lambda title: BookShelf(title))
>  
> If not, I propose that it be added.

Note that you can easily write a type like that yourself, using
dict.__missing__:

class DefShelfDict(dict):
     def __missing__(self, key):
         shelf = self[key] = BookShelf(key)
         return shelf

or some such.

Georg

-- 
Thus spake the Lord: Thou shalt indent with four spaces. No more, no less.
Four shall be the number of spaces thou shalt indent, and the number of thy
indenting shall be four. Eight shalt thou not indent, nor either indent thou
two, excepting that thou then proceed to four. Tabs are right out.



More information about the Python-3000 mailing list