On Apr 10, 2020, at 15:53, Steele Farnsworth <swfarnsworth@gmail.com> wrote:

I have implemented a class in the C code of the collections module which has similar behavior to the defaultdict class. This class, dynamicdict, supplies values for keys that have not yet been added using a default factory callable, but unlike defaultdict, the missing key itself is passed to the callable. This code can be seen here: https://github.com/swfarnsworth/cpython/blob/3.8/Modules/_collectionsmodule.c#L2234

That sounds like exactly the functionality for dict.__missing__, which is already there. Why can’t you just subclass dict and override that? Is it a readability issue, or a performance issue, or do you need to have a factory function that’s different per instance or accessible as an attribute or some other feature exactly like defaultdict, or…?

There might well be a good answer to one of these—although unless that good answer is performance, it seems like this should be a 5-line class in Python, not a custom C class. (Keep in mind that defaultdict was added somewhere around 2.4 or 2.5, while __missing__ has only been there since somewhere around 2.7/3.3. I’ll bet it would be different if it were invented today.)