4

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?

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I have seen the same error with a simple print function, can anyone reproduce? def print_path(path): print("In Python") print("Path:"+ path) print("Out Python") return True if __name__ == '__main__': message = "Hey D" print_path(message)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.