Double-Staring without sub-classing

Double-staring can be implemented on a type without sub-classing dict or Mapping. The sufficient requirements are:

  1. Implements __getitem__
  2. Implements keys
There are many creative use-cases for this API: expanding instances as keyword-arguments, implementing dict-by-part builders, restricting the API of otherwise-dict-like types, exposing __dict__, etc.

class DictLike:
    def __init__(self, *items, **mapping):
        self._dict = dict(*items, **mapping)

    def keys(self):
        return self._dict.keys()

    def __getitem__(self, key):
        return self._dict[key]

The __missing__ fallback

This dictionary sub-class implements __missing__, which computes a value as a fallback for a failed __getitem__ (ex: change KeyError to a custom Exception subclass)

class Dataset(dict):
    # double-star-iterable
    def keys(self):
        return self.keys()
    def __getitem__(self, k):
        return self.__getitem__(k)
    # fallback
    def __missing__(self, key):
        return 'missing: %s' % key

Converting arrays into dict

For item arrays, e.g. ((k1, v1), (k2, v2), ...), the dict constructor is directly used. The following functions implement the conversion from other common array shapes.


def eqsplit(cls, *_: str):
    # from ('k1=v1', 'k2=v2', ...)
    return cls(p.split('=', 1) for p in _)

def pairwise(cls, *_: str):
    # from (k1, v1, k2, v2, ...)
    return cls(zip(_[:-1:2], _[1::2]))