Idiomatic Python: 'times' loop [duplicate] Idiomatic Python: 'times' loop [duplicate] python python

Idiomatic Python: 'times' loop [duplicate]


You've already shown the idiomatic way:

for _ in range(n): # or xrange if you are on 2.X    foo()

Not sure what is "hackish" about this. If you have a more specific use case in mind, please provide more details, and there might be something better suited to what you are doing.


If you want the times method, and you need to use it on your own functions, try this:

def times(self, n, *args, **kwargs):    for _ in range(n):        self.__call__(*args, **kwargs)import newdef repeatable(func):    func.times = new.instancemethod(times, func, func.__class__)    return func

now add a @repeatable decorator to any method you need a times method on:

@repeatabledef foo(bar):    print barfoo.times(4, "baz") #outputs 4 lines of "baz"


Fastest, cleanest is itertools.repeat:

import itertoolsfor _ in itertools.repeat(None, n):    foo()