0

I'm trying to return the answer of the code below into a variable, the variable should change every 5 seconds therefore I can't use 'return' since it ends the function.

example:

from time import sleep

def printit():
    cpt = 1
    while True:
        if cpt < 3:
            number = ("images[" + str(cpt) + "].jpg")
            return number #here is the return
            sleep(5)
            cpt+=1
        else:
            printit()

answer = printit() 
print(answer) #only 1 answer is printed, then the function ends because of the 'return'

What is the solution to resolve this problem?

The variable answer should change every 5 seconds without ending the function.

Horai Nuri
  • 5,358
  • 16
  • 75
  • 127
  • 6
    A job for generators https://wiki.python.org/moin/Generators or closures http://www.shutupandship.com/2012/01/python-closures-explained.html?m=1 – dylan7 Dec 21 '15 at 18:53

2 Answers2

7

What is the solution to resolve this problem? The variable answer should change every 5 seconds without ending the function.

Here's one approach based on generator functions

from time import sleep

def printit():
    cpt = 1
    while True:
        if cpt < 3:
            number = ("images[" + str(cpt) + "].jpg")
            yield number #here is the return
            sleep(5)
            cpt+=1
        else:
            for number in printit():
                yield number


for number in printit():
    print number

This will keep the process running until the for loop receives no more values. To stop it gracefully, you can send a value into the generator:

gen = printit()
for i, number in enumerate(gen):
    print i, number
    if i > 3:
        try: 
            gen.send(True)
        except StopIteration:
            print "stopped"

For this to work, amend the yield statements as follows:

(...)
stop = yield number #here is the return
if stop:
   return
(...)

Depending on what you want to achieve this may or may not provide sufficient levels of concurrency. If you want to know more about generator-based coroutines, these very insightful papers and videos by David Beazley are a trove.

miraculixx
  • 10,034
  • 2
  • 41
  • 60
0

If you want an infinite count, you should use itertools.count with a generator function which would allow you to write your code succinctly:

from itertools import count
from time import sleep

def printit():
    cn = count(1)
    for i in iter(cn.next, 0):
        yield "images[{}].jpg".format(i)
        sleep(5)

for answer in printit():
    print(answer)
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321