Relational Python: Basic class for relations


A relation is basically a set of dictionaries (called tuples) where each dictionary has identical keys (called attributes).

While, as you'll see in the next couple of posts in this series, my display routine and the initial relational operators work on iterations over plain Python dictionaries, I found it useful to implement a relation, at least in these preliminary stages, using a different internal structure (something Date is clear in his book he has no problem with).

Basically, I store the each tuple internally as a Python tuple rather than a dictionary and the relation also keeps an ordered list of the attributes which is used as the index into the tuples. Amongst other things, this gets around dictionaries not being hashable. It's also a storage optimization akin to using slots for Python attributes.

class Rel:

def __init__(self, attributes): self.attributes_ = tuple(attributes) self.tuples_ = set()

def add(self, tup): self.tuples_.add(self._convert_dict(tup))

def _convert_dict(self, tup): return tuple([tup[attribute] for attribute in self.attributes_])

def attributes(self): return set(self.attributes_)

def tuples(self): for tup in self.tuples_: tupdict = {} for col in range(len(self.attributes_)): tupdict[self.attributes_[col]] = tup[col] yield tupdict

Note that Rel.attributes and Rel.tuples return a set of attributes and a generator over dictionaries just as you would expect.

By implementing the handy little helper function:

def d(**args): return args

we can now create a relation and add tuples like so:

rel1 = Rel(["ENO", "ENAME", "DNO", "SALARY"])

rel1.add(d(ENO="E1", ENAME="Lopez", DNO="D1", SALARY="40K")) rel1.add(d(ENO="E2", ENAME="Cheng", DNO="D1", SALARY="42K")) rel1.add(d(ENO="E3", ENAME="Finzi", DNO="D2", SALARY="30K"))

In the next post I'll share my display routine and, following that, start on the relational operators, beginning with PROJECT.

The original post was in the categories: python relational_python but I'm still in the process of migrating categories over.

The original post had 4 comments I'm in the process of migrating over.