Reputation: 418
In Python, a thread to call a function called check_values
is created as follows:
checking_thread = threading.Thread(target=check_values)
My question is why are the parentheses omitted for check_values
?
What happens if they're included?
Upvotes: 4
Views: 308
Reputation: 87124
Functions in Python are first class objects. They can be passed around as arguments to functions, assigned to variables, or invoked by "calling" them. The syntax to call a function is to reference the function name and immediately follow it with parentheses. Arguments can be passed to the function by listing them between the parentheses. Example:
def check_values(x=0):
print(x)
>>> check_values
<function check_values at 0x7fae489c7ea0>
>>> type(check_values)
<class 'function'>
>>> check_values()
0
>>> check_values(10)
10
>>> print(check_values)
<function check_values at 0x7fae488df400>
So check_values
is a reference to the function object and you can see it's an object by typing its name. It can be called by using parentheses, with an optional argument in this case. Finally, you can see the function being passed as an argument to the print()
function.
So to answer your question:
checking_thread = threading.Thread(target=check_values)
this passes a reference to the function named check_values
as the target
argument to the threading.Thread
function without calling function check_values
.
If you want to have threading.Thread
call the function with arguments then you need to pass those separately, e.g.
checking_thread = threading.Thread(target=check_values, args=(100,))
Upvotes: 1