The Python Oracle

python- how to get the output of the function used in Timer

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Music Box Puzzles

--

Chapters
00:00 Python- How To Get The Output Of The Function Used In Timer
00:34 Accepted Answer Score 5
01:00 Answer 2 Score 3
01:46 Thank you

--

Full question
https://stackoverflow.com/questions/2518...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #timer

#avk47



ACCEPTED ANSWER

Score 5


The return value of the function is just dropped by Timer, as we can see in the source. A way to go around this, is to pass a mutable argument and mutate it inside the function:

def work(container):
    container[0] = True

a = [False]
t = Timer(10, work, args=(a,))
t.start()

while not a[0]:
    print "Waiting, a[0]={0}...".format(a[0])
    time.sleep(1)

print "Done, result: {0}.".format(a[0])

Or, use global, but that's not the way a gentleman goes.




ANSWER 2

Score 3


Timer objects wait and execute the callback function in a separate thread. If you want to return a value, you need to set up some kind of inter-thread communication. The easiest way to do this would be to set a global variable and have it modified by the callback function:

from threading import Timer
import time

return_val = None

def timeout():

    global return_val
    return_val = True
    return

a = False    
t = Timer(10,timeout)
t.start()
count = 0

while not a:
    print count

    time.sleep(1)
    if return_val:
        break

    count += 1

print 'done'

Output:

0
1
2
3
4
5
6
7
8
9
done

I know globals are often frowned upon, but they can be fine if used carefully. My usage here is limited strictly to the case where I am establishing shared memory to be modified by only one thread and precision is not critical.