[Python-ideas] dict.setdefault_call(), or API variations thereupon

Guido van Rossum guido at python.org
Thu Nov 1 22:20:04 EDT 2018


The two are less connected than you seem to think.

On Thu, Nov 1, 2018 at 7:08 PM Alex Shafer <ashafer01 at gmail.com> wrote:

> I had actually managed to miss collections.defaultdict!
>
> I'd like to instead propose that a reference to that be added to the
> dict.setdefault docs. I can't imagine I'm the only one that has missed this.
>
>
> Date: Fri, 2 Nov 2018 12:12:45 +1100
>> From: Chris Angelico <rosuav at gmail.com>
>> To: python-ideas <python-ideas at python.org>
>> Subject: Re: [Python-ideas] dict.setdefault_call(), or API variations
>>         thereupon
>> Message-ID:
>>         <
>> CAPTjJmqg_qtK3OfR+4VAaaNa7JXjHjHLpnx6EfEZX5n4tttqCQ at mail.gmail.com>
>> Content-Type: text/plain; charset="UTF-8"
>
>
>>
>> On Fri, Nov 2, 2018 at 12:07 PM Alex Shafer <ashafer01 at gmail.com> wrote:
>> > Other APIs I've considered for this are a new keyword argument to the
>> existing `setdefault()`, or perhaps more radically for Python, a new
>> keyword argument to the `dict()` constructor that would get called as an
>> implicit default for `setdefault()` and perhaps used in other scenarios
>> (essentially defining a type for dict values).
>> >
>>
>> The time machine has been put to good use here. Are you aware of
>> __missing__ and collections.defaultdict? You just create a defaultdict
>> with a callable (very common to use a class like "list"), and any time
>> you try to use something that's missing, it'll call that to generate a
>> value.
>>
>> from collections import defaultdict
>> d = defaultdict(list)
>> for category, item in some_stuff:
>>     d[category].append(item)
>>
>> Easy way to group things into their categories.
>>
>> ChrisA
>>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
-- 
--Guido (mobile)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20181101/cda44473/attachment.html>


More information about the Python-ideas mailing list