I have built this data structure countless times. So I am in favor.
Why can’t you just subclass dict and override that?
Because TypeError: multiple bases have instance lay-out conflict is one of
my least favorite errors.
Perhaps `__missing__` could be a first class part of the getitem of
protocol, instead of a `dict` specific feature. So that
```
r = x[key]
```
means:
```
try:
r = x.__getitem__(key)
except KeyError as e: # should we also catch IndexError?
try:
missing = x.__missing__
except AttributeError:
raise e from None
r = missing(key)
```
Obviously this would come at some performance cost for non dict mappings so
I don't know if this would fly.
So instead maybe there could have standard decorator to get the same
behavior?
```
def usemissing(getitem):
@wraps(getitem)
def wrapped(self, key):
try:
return getitem(self, key)
except KeyError as e:
try:
missing = self.__missing__
except AttributeError:
raise e from None
return missing(key)
return wrapped
```
Alternatively, it could be implemented as part of one of the ABCs maybe
something like:
```
class MissingMapping(Mapping):
# Could also give MissingMapping its own metaclass
# and do the modification of __getitem__ there.
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
cls.__getitem__ = usemissing(cls.__getitem__)
@abstractmethod
def __missing__(self, key): pass
```
Caleb Donovick
On Fri, Apr 10, 2020 at 6:39 PM Steven D'Aprano
On Fri, Apr 10, 2020 at 06:02:25PM -0700, Andrew Barnert via Python-ideas wrote:
(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.)
Both `__missing__` and `defaultdict` were added in version 2.5.
https://docs.python.org/2/library/stdtypes.html#dict https://docs.python.org/2/library/collections.html#defaultdict-objects
-- Steven _______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-leave@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/HARDO2... Code of Conduct: http://python.org/psf/codeofconduct/