[Python-ideas] dict.setdefault_call(), or API variations thereupon
Steven D'Aprano
steve at pearwood.info
Thu Nov 1 23:34:11 EDT 2018
On Thu, Nov 01, 2018 at 08:58:28PM -0600, Alex Shafer wrote:
> So it actually sounds like having a dict method for performing write
> operations with a factory function would be a semantic improvement.
As Chris pointed out, that's what __missing__ does.
py> class MyDict(dict):
... def __missing__(self, key):
... return "something"
...
py> d = MyDict(a=1, b=2)
py> d['z']
'something'
py> d
{'a': 1, 'b': 2}
If you want the key to be inserted, do so in the __missing__ method.
Is there something missing (pun not intended) from this existing
functionality?
The only improvement I'd like to see is to remove the need to subclass,
so we could do this:
py> d = {'a': 1} # Plain ol' regular dict, not a subclass.
py> d.__missing__ = lambda self, key: "something"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute '__missing__'
but as you can see, that doesn't work. We'd need to either give every
dict a full __dict__ instance namespace, or a __missing__ slot. Given
how rare it is to use __missing__ I suspect the cost is not worth it.
The bottom line is, if I understand your proposal, the functionality
already exists. All you need do is subclass dict and give it a
__missing__ method which does what you want.
--
Steve
More information about the Python-ideas
mailing list