Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Omitted parentheses from target function

Tags:

python

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?

like image 650
SomebodyOnEarth Avatar asked Apr 10 '26 10:04

SomebodyOnEarth


1 Answers

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,))
like image 101
mhawke Avatar answered Apr 12 '26 00:04

mhawke



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!