enumerate is very useful and now "progresserate"

Brian Kelley bkelley at wi.mit.edu
Wed Nov 19 20:10:58 CET 2003


It also inspired me to write "progresserate" which returns the percent 
completed of the list and the current value.

class progresserate:
     def __init__(self, sequence):
         self.size = float(len(sequence))
         self.iterator = iter(sequence)
         self.i = 0
         self.last = None

     def __iter__(self):
         return self

     def next(self):
         value = self.iterator.next()
         self.i += 1
         percent = int(self.i/self.size * 100)
         return percent, value

for percent, value in progresserate([1,2,3]):
     print "percent complete", percent, "value", value

output
percent complete 33 value 1
percent complete 66 value 2
percent complete 100 value 3

This is useful for updating progress bars and the like.  I use it all 
the time, it sure saves code duplication.

Is this idea something that is useful enough for inclusion in the 
standard library?  (Not this code as-is, I don't show error checking for 
brevity's sake)

One stylistic question, I tend to use
def __iter__(self): return self

when writing these styles of iterators.  It kind of bugs me, is there a 
better alternative?

Brian





More information about the Python-list mailing list