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

Time:04-25

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?

CodePudding user response:

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

CodePudding user response:

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
  • Related