Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does threading.Timer avoid recursion in Python?

I found a code snippet in stackoverflow (Run certain code every n seconds) that runs a function after every n seconds.

import threading

def printit():
  threading.Timer(5.0, printit).start()
  print "Hello, World!"

printit()

I tried to do the same with my code and of course I got RecursionError: maximum recursion depth exceeded while calling a Python object

import time

def call_f_after_n_secs(f, n):
    time.sleep(n)
    f()

def my_fun():
    print("my_fun")
    call_f_after_n_secs(my_fun, 0.01)

my_fun()

My question is, how does threading.Timer avoid maximum recursion depth ? I mean (except from the part of threading that "detaches" the code from the main flow of the program) how does Timer work internally and calls printit() without making recursive calls ?


1 Answers

"except from the part of threading that "detaches" the code from the main flow of the program"

You can't understand it without that part. The original setup doesn't introduce recursion in the first place because printit() gets called in another thread. Every thread has its own stack and the first thread never adds another call to printit() to it. The original thread just initializes a new Thread-object and the new thread itself calls printit() after it bootstraps.

like image 189
Darkonaut Avatar answered Nov 09 '25 09:11

Darkonaut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!