
February 12th, 2013, 07:08 PM
|
 |
Contributing User
|
|
|
|
|
This answer is ridiculous.
The attributes of the class are data driven. Why are the generic objects better than dictionaries? I can't think of a reason. One could insert a price method that depends on item featues, and that would be a good reason to use a custom class instead of a dictionary. The class is restrictive, the keys need to be valid python identifiers.
Code:
import io
import sys
import csv
import pprint
class generic(dict):
pass
def generic_factory(file_object):
reader = iter(csv.reader(file_object))
attributes = next(reader)
result = []
try:
while True:
row = next(reader)
kwargs = dict(zip(attributes,row))
result.append(generic(**kwargs))
except StopIteration:
pass
return result
DATA = '"partID","partName"\n35553,"snare"\n28709,"rim"\n85332,"skin"'
if sys.version[0] == '2':
DATA = DATA.decode('utf8')
FAKEFILE = io.StringIO(DATA)
FAKEFILE.seek(0)
OBJECTS = generic_factory(FAKEFILE)
FAKEFILE.close()
pprint.pprint([str(O) for O in OBJECTS])
It occurs to me this is easier:
Code:
import io
import sys
import csv
import pprint
DATA = '"partID","partName"\n35553,"snare"\n28709,"rim"\n85332,"skin"'
if sys.version[0] == '2':
DATA = DATA.decode('utf8')
with io.StringIO(DATA) as FAKEFILE:
FAKEFILE.seek(0)
OBJECTS = [O for O in csv.DictReader(FAKEFILE)]
pprint.pprint([str(O) for O in OBJECTS])
__________________
[code] Code tags[/code] are essential for python code!
Last edited by b49P23TIvg : February 12th, 2013 at 07:10 PM.
|