kurtbrose / relativity

relational python object data structures
MIT License
8 stars 2 forks source link

M2M.getone() #8

Open kurtbrose opened 1 year ago

kurtbrose commented 1 year ago

Need a way to reduce arity back down.

One possibility is getone(). This might be confusing since getall() is multiple keys -> multiple values, get() is one key -> multiple values, and getone() is one key -> one value.

Currently this is quite ugly: m2m.get(key, [None])[0] this could be m2m.getone(key)

Maybe getany() would be a clearer name -- this will return an arbitrary match if there is one.

kurtbrose commented 1 year ago
def getany(self, key, default=None):
   if key not in self.data:
      return default
   return next(iter(self.data[key]))
kurtbrose commented 1 year ago
def _join_maps(*maps) -> dict:
  """
  Given a series of maps, which can either be dicts, or [(key, val)],
  join them together in the order they are passed in, and return a map from
  the left most keys to the right-most values.
  For example, _join_maps({1: 'one'}, {'one': 'uno'}) -> {1: 'uno'}

  Any missing values will be replaced with None.
  For example, _join_maps({1: 'one'}, {'two': 'dos'}) -> {1: None}
  """
  missing_nones = dict(relativity.chain(*[relativity.M2M(map) for map in maps]).pairs(0, len(maps)).iteritems())
  return {key: missing_nones.get(key) for key in maps[0]}

This is essentially what I was trying to do.