From 1bbef1f1b8aaaa449971d06990258b3070abc000 Mon Sep 17 00:00:00 2001 From: Salvo 'LtWorf' Tomaselli Date: Sat, 15 Aug 2020 20:54:58 +0200 Subject: [PATCH] function to load a relation from iterators --- relational/relation.py | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/relational/relation.py b/relational/relation.py index 692db90..d9f1703 100644 --- a/relational/relation.py +++ b/relational/relation.py @@ -62,12 +62,30 @@ class Relation(NamedTuple): @staticmethod def load(filename: Union[str, Path]) -> 'Relation': + ''' + Load a relation object from a csv file. + + The 1st row is the header and the other rows are the content. + ''' with open(filename) as fp: reader = csv.reader(fp) # Creating a csv reader header = Header(next(reader)) # read 1st line - #FIXME load properly - content = frozenset((tuple(Rstring(s) for s in i) for i in reader)) - return Relation(header, content) + return Relation.create_from(header, reader) + + @staticmethod + def create_from(header: Iterable[str], content: Iterable[Iterable[str]]) -> 'Relation': + ''' + Iterator for the header, and iterator for the content. + ''' + header = Header(header) + r_content: List[Tuple[Rstring, ...]] = [] + for row in content: + content_row: Tuple[Rstring, ...] = tuple(Rstring(i) for i in row) + if len(content_row) != len(header): + raise ValueError(f'Line {row} contains an incorrect amount of values') + r_content.append(content_row) + return Relation(header, frozenset(r_content)) + def __iter__(self): return iter(self.content)