Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic Python: 'times' loop [duplicate]

Say I have a function foo that I want to call n times. In Ruby, I would write:

n.times { foo } 

In Python, I could write:

for _ in xrange(n): foo() 

But that seems like a hacky way of doing things.

My question: Is there an idiomatic way of doing this in Python?

like image 898
perimosocordiae Avatar asked Apr 17 '10 03:04

perimosocordiae


People also ask

What are loop idioms in Python?

Loops are the way we tell Python to do something over and over. Loops are the way we build programs that stay with a problem until the problem is solved. 5.1 - Loops and Iteration9:37. 5.2 - Definite Loops6:28.

How do you repeat a program and time in Python?

In Python, we utilize the asterisk operator to repeat a string. This operator is indicated by a “*” sign. This operator iterates the string n (number) of times. The “n” is an integer value.


2 Answers

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.

like image 135
TM. Avatar answered Oct 03 '22 01:10

TM.


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 new def 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:

@repeatable def foo(bar):     print bar  foo.times(4, "baz") #outputs 4 lines of "baz" 
like image 30
Carson Myers Avatar answered Oct 03 '22 00:10

Carson Myers