So, going back to the original post, dynamicdict is definitely something I've reimplemented myself multiple times essentially exactly as your pseudo-code in your C-command describes, just with the factory being required to be not None (because I explicitly didn't want it to accept the 'no-factory' case:

class dynamic_defaultdict(dict):
    def __init__(self, default_factory, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._default_factory = default_factory

    def __missing__(self, key):
         self[key] = value = self._default_factory(key)
         return value

But I actually have used this quite a bit without significant issues and don't fully understand the layout issue described.  It seems to work with dict equality as well, but I'm also super new to this list so maybe I'm just naive and don't understand the nuance.

-Jeff Edwards

On Thu, Apr 16, 2020 at 7:35 PM Andrew Barnert via Python-ideas <> wrote:
On Apr 16, 2020, at 12:26, Andrew Barnert <> wrote:
> Somewhere I have some code for a set of class decorators that help implementing mappings and sequences: you provide basic __fooitem__ methods, and it wraps them with methods that do all the extra stuff dict, tuple, and list do. IIRC, the mutable sequence stuff is the only place where it gets complicated, but there may be others I haven’t remembered. I can dig this up if you‘re interested. Maybe it’s even worth cleaning up and posting to PyPI, or even proposing for somewhere in the stdlib (collections or functools?).

Ok, I found it, and it’s in better shape than I thought it was. (It even passes all the relevant tests from the stdlib test suite.) So I posted it on in case anyone wants to play with it. If there’s any demand for turning it into a PyPI package, I can do that, but otherwise I won’t bother.

Anyway, if you look at the code, most of it is devoted to the mutable sequence __setitem__, but making mapping __getitem__ handle __missing__ wasn’t quite as trivial as you’d expect (it breaks the __contains__ and get methods you inherit from Mapping…). Whether that counts as an argument for or against any version of the various proposals in this thread, I’m not sure.

Python-ideas mailing list --
To unsubscribe send an email to
Message archived at
Code of Conduct: