Search code examples
pythonpython-multithreading

RecursionError: maximum recursion depth exceeded while using thread


So I am getting the error

[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded

The code I am running is

import threading

def hello_world(a):
    threading.Timer(2.0, hello_world(a)).start() # called every minute
    print(a)
    print("Hello, World!")

hello_world('a')

I noticed that when there are no arguments in the hello_world function the error doesn't occur. But as soon as I need to pass in a parameter to the function I get the error. Can someone explain why that is the case and how to fix it?


Solution

  • The threading.Timer() constructor expects the function and the arguments to pass to that function as separate parameters. The proper way to call it is this:

    threading.Timer(2.0, hello_world, (a,)).start()
    

    You can see that we refer to hello_world without calling it, and we list the parameters we want to pass separately in a 1-tuple (a,).

    The way you're currently doing it, it's evaluating hello_world(a) immediately, before it gets to the end of the expression, trying to figure out what the return value of hello_world(a) would be - as opposed to starting the timer and then evaluating the expression every time the timer goes off.