Re:Dear Python
by jmillikin on Tuesday February 02, 2010 @09:27PM
(#1096896)
The preferred way to do that in Python is as a co-routine (AKA generator). Besides being easier to read and reason about, generators implement common protocols, such as the iteration protocol. This means you can use generators in for-loops, as a parameter to list(), or anywhere else that accepts an iterator.
Here's an example of cycle() as a co-routine:
def cycle(*args):
i = 0
while True:
i = (i + 1) % len (args)
yield args[i]
for arg in cycle("red", "green", "blue"):
print (arg)
Alternatively, if you really want to use a callable:
Here's an example of cycle() as a co-routine:
Alternatively, if you really want to use a callable: Either way, it'll be cleaner than an explicitly stateful object.