I want to loop over a number of rows in a database and I have implemented an object in order to access the rows. Now when using this object I am not sure about the best practice. Implementing an iterator looks nice in the higher-level script but is somewhat unnecessary.
So I wondered, what are the benefits and disadvantages of looping over a list vs. a 'proper' iterator?
Alternatively, would either option make more sense if I changed the structure of my object?
Here is my code using python 2.7:
class process_scope(object):
__columns = ['id', 'type', 'start', 'end', 'seconds', \
'static', 'table_ref']
def __init__(self, force = False):
self.force = force
self._load_timeframes()
self._reduce_timeframes()
def __iter__(self):
return self
def next(self):
try:
return self.timeframes.pop()
except IndexError:
raise StopIteration
def _load_timeframes(self):
self.timeframes = ((1, 'type_1', 000, 999, 999, 0, 'table_1'),
(2, 'type_2', 000, 999, 999, 0, 'table_2'),
(3, 'type_3', 000, 999, 999, 1, 'table_3'),
(4, 'type_2', 000, 999, 999, 0, 'table_4'),
(5, 'type_1', 000, 999, 999, 0, 'table_5'))
def _reduce_timeframes(self):
relevant_timeframes = []
for tf in self.timeframes:
tf = dict(zip(process_scope.__columns, tf))
if tf['static'] == 0 or self.force:
relevant_timeframes.append(tf)
self.timeframes = relevant_timeframes
Here is the usage option utilizing the iterator...:
for i in process_scope():
print i
...and the option without implementing the iterator:
iter_ = process_scope().timeframes
for i in iter_:
print i
self.timeframesisn't a good way to implement the iterable here. Just make__iter__returniter(self.timeframes).next()method?nextif the instance itself is the iterator (hence it's required when youreturn selffrom__iter__).nextis implemented by the objectiterreturns.