Guido's on_missing() proposal is pretty good for what it is, but it is not a replacement for set_default(). The use cases for a derivable, definition or instantiation time framework is different than the call-site based decision being made with setdefault(). The difference is that in the former case, the class designer or instantiator gets to decide what the default is, and in the latter (i.e. current) case, the user gets to decide.
Going back to first principles, the two biggest problems with today's setdefault() is 1) the default object gets instantiated whether you need it or not, and 2) the idiom is not very readable. To directly address these two problems, I propose a new method called getdefault() with the following signature: def getdefault(self, key, factory) This yields the following idiom: d.getdefault('foo', list).append('bar') Clearly this completely addresses problem #1. The implementation is simple and obvious, and there's no default object instantiated unless the key is missing. I think #2 is addressed nicely too because "getdefault()" shifts the focus on what the method returns rather than the effect of the method on the target dict. Perhaps that's enough to make the chained operation on the returned value feel more natural. "getdefault()" also looks more like "get()" so maybe that helps it be less jarring. This approach also seems to address Raymond's objections because getdefault() isn't "special" the way on_missing() would be. Anyway, I don't think it's an either/or choice with Guido's subclass. Instead I think they are different use cases. I would add getdefault() to the standard dict API, remove (eventually) setdefault(), and add Guido's subclass in a separate module. But I /wouldn't/ clutter the built-in dict's API with on_missing(). -Barry P.S. _missing = object() def getdefault(self, key, factory): value = self.get(key, _missing) if value is _missing: value = self[key] = factory() return value
signature.asc
Description: This is a digitally signed message part
_______________________________________________ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com