user12546101
user12546101

Reputation:

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 ?

Upvotes: 4

Views: 960

Answers (1)

Darkonaut
Darkonaut

Reputation: 21654

"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.

Upvotes: 2

Related Questions