3 ms·
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,
by jmillikin 17y ago
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:
gencycle = lambda *args: cycle(*args).next
get_next = gencycle("red", "green", "blue")
print (get_next())
print (get_next())
print (get_next())
Either way, it'll be cleaner than an explicitly stateful object.