enumerate is very useful and now "progresserate"

Francis Avila francisgavila at yahoo.com
Wed Nov 19 18:41:26 EST 2003


Brian Kelley wrote in message
<3fbbbffd$0$577$b45e6eb0 at senator-bedfellow.mit.edu>...
>It also inspired me to write "progresserate" which returns the percent
>completed of the list and the current value.


>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)


It's very neat (I always seem to want to turn every problem into a generator
problem :).  But actually, in this case (unless that error checking code you
mention forbids it), you don't need a class.  The only methods you define
are for the generator protocol, and none of them have arguments.  So a
generator function is enough (and undoubtably faster):

def progresserate(seq):
    size = float(len(seq))
    iterator = iter(seq)
    i = 0
    #what did self.last do?
    while True: #StopIteration from iterator will propagate.
        value = iterator.next()
        i += 1
        percent = int(i/size * 100)
        yield percent, value


>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?

Could you be more specific?  What bugs you about it?

If it's the 'self' you mean, then know that that corresponds exactly to the
behavior of iterators currently: if you request an iterator from an
iterator, it returns itself (what else would it return?).  If you want a
*copy* of an iterator,  you have to wait until PEP 323.
--
Francis Avila






More information about the Python-list mailing list