How to say $a=$b->{"A"} ||={} in Python?

Carl Banks pavlovevidence at gmail.com
Fri Aug 17 20:02:31 EDT 2007


On Aug 16, 10:01 pm, Paul McGuire <pt... at austin.rr.com> wrote:
> On Aug 16, 8:28 pm, Jonathan Gardner
>
>
>
> <jgardner.jonathangardner.... at gmail.com> wrote:
> > On Aug 16, 3:35 pm, beginner <zyzhu2... at gmail.com> wrote:
>
> > > In perl it is just one line: $a=$b->{"A"} ||={}.
>
> > a = b.setdefault('A', {})
>
> > This combines all two actions together:
> > - Sets b['A'] to {} if it is not already defined
> > - Assigns b['A'] to a
>
> > More info on dict methods here:
>
> >http://docs.python.org/lib/typesmapping.html
>
> No, this has already been proposed and discarded.  The OP does NOT
> want this, because it always generates an empty {} whether it is
> needed or not.  Not really a big hardship, but if the default value
> were some expensive-to-construct container class, then you would be
> creating one every time you wanted to reference a value, on the chance
> that the key did not exist.
>
> Carl Banks' post using defaultdict is the correct solution.  The
> raison d'etre for defaultdict, and the reason that it is the solution
> to the OP's question, is that instead of creating a just-in-case
> default value every time, the defaultdict itself is constructed with a
> factory method of some kind (in practice, it appears that this factory
> method is usually the list or dict class constructor).  If a reference
> to the defaultdict gives a not-yet-existing key, then the factory
> method is called to construct the new value, that value is stored in
> the dict with the given key, and the value is passed back to the
> caller.  No instances are created unless they are truly required for
> initializing an entry for a never-before-seen key.


When I made my response, it occurred to me that Python could be
improved (maybe) if one could overload dict.get() to use a factory,
like so:

b = {}
a = b.get(k,factory=dict)
a['A'] = 1

That's a slight improvement (maybe) over defaultdict since it would
still allow the same dict to have the membership check in other
places.  I'm not so sure overloading get to let it modify the dict is
a good idea, though.

Actually, it'd probably be fairly uncontroversial to add a factory
keyword to dict.setdefault().  At least insofar as setdefault is
uncontroversial.


Carl Banks




More information about the Python-list mailing list