[Tutor] question about descriptors
Peter Otten
__peter__ at web.de
Wed Nov 11 13:28:52 EST 2015
Albert-Jan Roskam wrote:
>> class ReadColumn(object):
>> def __init__(self, index):
>> self._index = index
>> def __get__(self, obj, type=None):
>> return obj._row[self._index]
>> def __set__(self, obj, value):
>> raise AttributeError("oops")
>
> This appears to return one value, whereas I wanted I wanted to return all
> values of a column, ie as many values as there are rows. But the logic
> probably won't change.
Sorry, I overlooked that aspect. If you want a whole column you either have
to iterate over the complete file and keep the data in memory or you need a
separate file descriptor for every access of a column. Here's an
implementation of the first:
def csv_columns(instream):
reader = csv.reader(instream, delimiter=";")
header = next(reader)
return namedtuple("Columns", header)._make(tuple(zip(*reader)))
More information about the Tutor
mailing list