Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #81768 > unrolled thread

Re: Setting default_factory of defaultdict to key

Started byLarry Martell <larry.martell@gmail.com>
First post2014-12-01 13:41 -0500
Last post2014-12-01 13:41 -0500
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Setting default_factory of defaultdict to key Larry Martell <larry.martell@gmail.com> - 2014-12-01 13:41 -0500

#81768 — Re: Setting default_factory of defaultdict to key

FromLarry Martell <larry.martell@gmail.com>
Date2014-12-01 13:41 -0500
SubjectRe: Setting default_factory of defaultdict to key
Message-ID<mailman.16464.1417459295.18130.python-list@python.org>
On Mon, Dec 1, 2014 at 1:36 PM, Ethan Furman <ethan@stoneleaf.us> wrote:
> On 12/01/2014 10:29 AM, Larry Martell wrote:
>> On Mon, Dec 1, 2014 at 1:19 PM, Ethan Furman <ethan@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]

Oops! Thanks. Working now.

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web