-from abc import abstractmethod
+from abc import abstractmethod, abstractclassmethod
from csv import DictReader, DictWriter, excel_tab
from copy import copy
from pathlib import Path
@abstractmethod
def __hash__(self):
- # Needed because line items are contained in sets, not lists.
- raise NotImplementedError
+ msg = f"Define hash so {self.__class__} can determine uniqueness."
+ raise NotImplementedError(msg)
@classmethod
def get_fieldnames(cls):
class NomList(set):
- def __init__(self, elements: Optional[Iterable[NomListItem]]=None):
- if not elements:
+ def __init__(self, items: Optional[Iterable]=None):
+ if not items:
super().__init__()
else:
- super().__init__(elements)
+ nlitems = [self.nlitem().from_dict(item.to_dict()) for item in items]
+ super().__init__(nlitems)
# Number items and persist via label attribute
- for i, item in enumerate(self, start=1):
- if not item.label:
- item.__setattr__('label',i)
+ for i, nlitem in enumerate(self, start=1):
+ if not nlitem.label:
+ nlitem.__setattr__('label',i)
+
+ @abstractclassmethod
+ def nlitem(cls):
+ msg = "You must specify what type of NomListItem the list contains."
+ raise NotImplementedError(msg)
def __add__(self, other):
return self.__class__(self.union(other))
for item in self.items:
print(item.to_str(delimeter="\t"))
-
@classmethod
- def from_csv(cls, file: Path, nlitem: NomListItem, delimiter="|"):
- # To parse NomListItems in a file, specify a specific NomListItem
- if nlitem == NomListItem or type(nlitem) == NomListItem:
- raise NotImplementedError(f"Override this method with super().__init__(file, {str(cls()).replace('()','')}Item) to enforce item parsing.")
+ def from_csv(cls, file: Path, delimiter="|"):
items = []
dialect = excel_tab
dialect.delimiter=delimiter
with open(file, "r") as f:
reader = DictReader(f,dialect=dialect)
for row in reader:
- item = nlitem.from_dict(row)
+ item = cls.nlitem().from_dict(row)
items.append(item)
return cls(items)