class RowError(Exception): """ error - a row is too long """ def __init__(self, values): Exception.__init__(self, values) class reader: """ reads relational data from a tsv reader """ def __init__(self, reader): self._reader = reader self._names = reader.read() self._degree = len(self._names) def read(self): values = self._reader.read() if not values: return None if len(values) != self._degree: raise RowError(values) pairs = map(None, self._names, values) row = {} for name, value in pairs: row[name] = value return row def names(self): return self._names def degree(self): return self._degree class writer: """ writes relational data to a tsv reader """ def __init__(self, writer, names): self._writer = writer self._names = names self._degree = len(names) writer.write(names) def write(self, row): if row == None: self._writer.write(None) return values = [] n = 0 for name in self._names: values.append(row[name]) n = n + 1 if n < self._degree: raise RowError(row) self._writer.write(values) def names(self): return self._names def degree(self): return self._degree class cut: """ applies a name-map to rows of a relation """ def __init__(self, pairs): self._pairs = pairs def cut(self, row): out = {} for n1, n2 in self._pairs: if row.has_key(n1): value = row[n1] if out.has_key(n2) and value != out[n2]: return None out[n2] = value return out