Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean when a Python function is called in the format f(x)(y)?

In this article, the following line of code is given an an example:

 x = layers.Dense(64, activation="relu", name="dense_1")(inputs)

This appears to be a function call which first passes in 64, then two named arguments, then passes in input.

What's going on here? Is inputs being passed to layers.Dense or something else?

like image 851
Terry Price Avatar asked Dec 29 '25 16:12

Terry Price


2 Answers

The function "Dense" returns something callable which gets called by the second pair of brackets.

For example:

def function1():
    return function2

def function2():
    print('Function 2')

x = function1()
x() # This will print "Function 2"

It is also possible to return classes. In this case the brackets will call the constructor thus creating an instance of the class.

def function1():
    return SomeClass

class SomeClass:
    def __init__(self):
        print("__init__")

x = function1()
x() # This will print "__init__"
like image 194
VarChar42 Avatar answered Jan 01 '26 06:01

VarChar42


You are basically providing an argument for the function returned by another function (wrapper function), which also known as inner function:

def funcwrapper(y):
    def addone(x):
        return x + y + 1
    return addone

print(funcwrapper(3)(2))

Output:

6
like image 40
Oghli Avatar answered Jan 01 '26 06:01

Oghli



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!