pythonoopkeraslanguage-construct

What is the programming construct in Python of passing some arguments in front of a constructor call? How to interpret parameters passed to an object?


In the below code line, if I am not mistaken, we are creating the object of the class layer.Dense from tensorflow.keras and then passing some arguments to the object in the parethesis. x = layers.Dense(128 * 16 * 16)(inputs). What is this programming construct in Python and what are we exactly doing here?

Note: layer.Dense is a class here.


Solution

  • That's just another function call. You basically have:

    <some expression>(inputs)
    

    So <some expression> evaluated to a function (or other callable).

    Here's a simple example:

    def adder_maker(n):
        def add_n(x):
            return x + n
        return add_n
    

    Then, you can do something like:

    adder_maker(2)(1)  # returns 3
    

    It may be more clear if you assign the intermediate result to a variable:

    add_2 = adder_maker(2)
    add_2(1) # returns 3
    

    One last point - arbitrary objects can be made callable in Python. e.g.

    class MyCallable:
        def __init__(self, value):
            self.value = value
        def __call__(self, x):
            return self.value + x
    
    f = MyCallable(2)
    f(1) # returns 3
    f.value = 99
    f(1) # returns 100
    

    So the expression doesn't have to evaluate to a function necessarily, which is just one kind of callable object.

    Here's another way of looking at it, in the expression

    x(<args>)
    

    The parentheses are just another operator, the "call operator" is just like a "+ operator" and objects can support using that operator if the implement __call__ (just like objects can support the + operator if they implement __add__)