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


Groups > comp.lang.python > #81769

Re: Setting default_factory of defaultdict to key

References <CACwCsY7sCi51Aq9z3vbSohG-gq-xHyo_=jXzS04FUVy1b8F5Qw@mail.gmail.com> <547CB12C.3010502@stoneleaf.us> <CACwCsY5oCdq5b0ZO3iXV21CutV91tF8=wwu+gpYDbC4X0=p0wQ@mail.gmail.com>
From Ian Kelly <ian.g.kelly@gmail.com>
Date 2014-12-01 11:35 -0700
Subject Re: Setting default_factory of defaultdict to key
Newsgroups comp.lang.python
Message-ID <mailman.16465.1417459396.18130.python-list@python.org> (permalink)

Show all headers | View raw


On Mon, Dec 1, 2014 at 11:29 AM, Larry Martell <larry.martell@gmail.com> wrote:
> I spoke too soon:
>
>>>> class defaultdictkey(defaultdict):
> ...  def __missing__(self, key):
> ...   self[key] = self.default_factory(key)
> ...
>>>> x = defaultdictkey(lambda k: k)
>>>> print x['aaa']
> None
>>>> print x['aaa']
> aaa
>>>> a = x['qqq']
>>>> print a
> None

You need to also return the value from __missing__.

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Setting default_factory of defaultdict to key Ian Kelly <ian.g.kelly@gmail.com> - 2014-12-01 11:35 -0700

csiph-web