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): try: 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, []) l.append(somevalue) # instead... for i in range(1000000): l = d.setdefault_call(somekey, list) l.append(somevalue) 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! PS 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).
_______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/