I'm trying to modify a class which has methods based on the csv module.
The data is a simple three-column csv file which I wanted to turn into a nested list of dictionaries.
I've managed to that with the help of this SO question.
However, I'd like to be able to implement a more general 'load_data' method, one which I could use decorators to introduce methods to output to take two columns of a loaded csv and output as a list of dictionaries.
My attempt to produce the wrapper function and proposed csv_to_dict_dicts method are commented out.
import csv
class AutoVivification(dict):
"""Implementation of perl's autovivification feature."""
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
value = self[item] = type(self)()
return value
"""
def csv_decorator(func):
def func_wrapper(self):
for row in reader:
return dict(self.data[row[0]][row[1]] = row[2] )
return func_wrapper
"""
class CSV:
def __init__(self):
self.data = AutoVivification()
def load_data(self, path):
with open(path, encoding="utf-8") as f:
self.path = path
reader = csv.reader(f)
for row in reader:
self.data[row[0]][row[1]] = row[2]
#@csv_decorator
#def csv_to_dict_dicts(self):
# return self.load_data(path)
c = CSV()
c.load_data(path)
UPDATE:
I've tried using SO question thus:
def csv_decorator(func):
def func_wrapper(self):
reader = func(self)
for row in reader:
self.data[row[0]][row[1]] = row[2]
return func_wrapper
class CSV:
def __init__(self):
self.data = AutoVivification()
@csv_decorator
def load_data(self, path):
with open(path, encoding="utf-8") as f:
self.path = path
reader = csv.reader(f)
return reader
However, I receive the error:
TypeError: func_wrapper() takes 1 positional argument but 2 were given