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?
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.
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.
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 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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With