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]
  r = x.__getitem__(key)
except KeyError as e: # should we also catch IndexError?
    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):
  def wrapped(self, key):
      return getitem(self, key)
    except KeyError as e:
        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):
    cls.__getitem__ = usemissing(cls.__getitem__)
  def __missing__(self, key): pass


Caleb Donovick

On Fri, Apr 10, 2020 at 6:39 PM Steven D'Aprano <steve@pearwood.info> wrote:
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.


Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-leave@python.org
Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/HARDO2LXJ72AUYJXCWKWNOYJW4PU56HG/
Code of Conduct: http://python.org/psf/codeofconduct/