Setting default_factory of defaultdict to key

Ethan Furman ethan at stoneleaf.us
Mon Dec 1 13:36:25 EST 2014


On 12/01/2014 10:29 AM, Larry Martell wrote:
> On Mon, Dec 1, 2014 at 1:19 PM, Ethan Furman <ethan at stoneleaf.us> wrote:
>> On 12/01/2014 10:05 AM, Larry Martell wrote:
>>>
>>> Is there a way to set the default_factory of defaultdict so that
>>> accesses to undefined keys get to set to the key?
>>
>> You need to subclass and modify __missing__ to actually pass along the key:
>>
>> --> class defaultdictkey(defaultdict):
>> ...   def __missing__(self, key):
>> ...     self[key] = self.default_factory(key)
>> ...     return self[key]
>> ...
>>
>> and in action:
>>
>> --> huh = defaultdictkey(lambda k: k)
>> --> huh
>> defaultdict(<function <lambda> at 0x7fe1305de3f0>, {})
>> --> huh['x']
>> 'x'
>> --> huh['x']
>> 'x'
>> --> huh.get('y')
>> --> huh['y']
>> 'y'
>> --> huh.get('y')
>> 'y'
> 
> 
> I spoke too soon:
> 
>>>> class defaultdictkey(defaultdict):
> ...  def __missing__(self, key):
> ...   self[key] = self.default_factory(key)

You missed the third line here ^

  ...   return self[key]

--
~Ethan~

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20141201/26475f6c/attachment.sig>


More information about the Python-list mailing list