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

Alex Shafer ashafer01 at gmail.com
Thu Nov 1 21:06:54 EDT 2018

I'd like to propose an addition to `dict` but I'm not necessarily proposing
what's written here as the API. When I initially saw the need for this
myself, I hastily wrote it as:

def setdefault_call(a_dict, key, default_func):
        return a_dict[key]
    except KeyError:
        default = default_func()
        a_dict[key] = default
        return default

If its not clear, the purpose is to eliminate the overhead of creating an
empty list or similar in situations like this:

d = {}
for i in range(1000000):  # some large loop
     l = d.setdefault(somekey, [])

# instead...

for i in range(1000000):
    l = d.setdefault_call(somekey, list)

One potential drawback I see to the concept is that I think there will be a
need to explicitly say "no arguments can get passed into this call".
Otherwise users may defeat the purpose with constructions like this:

d.setdefault_call("foo", list, ["default value"])

I'd mainly like feedback on this concept overall, and if its liked, perhaps
an API discussion to follow. Thanks!


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).
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20181101/46575043/attachment.html>

More information about the Python-ideas mailing list