Terry Price
Terry Price

Reputation: 327

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?

Upvotes: 2

Views: 110

Answers (2)

Oghli
Oghli

Reputation: 2340

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

Upvotes: 1

VarChar42
VarChar42

Reputation: 805

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__"

Upvotes: 8

Related Questions