Does anyone else use this little idiom?

Paul McGuire ptmcg at austin.rr.com
Sun Feb 3 11:20:19 EST 2008


On Feb 2, 9:48 pm, Jeff Schwab <j... at schwabcenter.com> wrote:
> How miller.pau... at gmail.com wrote:
> > Ruby has a neat little convenience when writing loops where you don't
> > care about the loop index: you just do n.times do { ... some
> > code ... } where n is an integer representing how many times you want
> > to execute "some code."
>
> Would something like this be acceptable?  It still requires a loop
> variable, plus an extra line of code per loop, plus a one-time class
> definition (and import into each client module), and it's probably
> slower than "for dummy in range."  The syntax might be more inuitive
> than "dummy" or "_" in a for loop, though.
>
> class Go:
>      def __init__(self, count):
>          self.count = count
>
>      def again(self):
>          if self.count <= 0:
>              return False
>          self.count -= 1
>          return True
>
> go = Go(3)
> while go.again():
>      print "hello"- Hide quoted text -
>
> - Show quoted text -

Here's something similar, in a decorator:

def iterative(fn):
    def times_(n):
        i = 0
        while i < n:
            fn()
            i += 1
    fn.times = times_
    return fn

@iterative
def aFunction():
    print "this is a function"

aFunction.times(3)

Prints:
this is a function
this is a function
this is a function

But this still seems like a lot of work to avoid "for x in range(n):".
-- Paul




More information about the Python-list mailing list