junmouse
junmouse

Reputation: 155

Python. Another bracket next to a function

I have code as below.

x = inputs
if conv_first:
    x = conv(x)
    if batch_normalization:
        x = BatchNormalization()(x)
    if activation is not None:
        x = Activation(activation)(x)

Here, I dont understand how x = BatchNormalization()(x) works (just like the same, x = Activation(activation)(x) too). If it was BatchNormalization(x), it would have been easy.

Anyone can explain in a concise way what it is and how it works?

Thank you very much in advance.

Upvotes: 1

Views: 301

Answers (2)

jfaccioni
jfaccioni

Reputation: 7519

Not sure that is the case, but the syntax is possible if the first called object returns another function.

Consider this code:

def f(arg):
    print(arg)

def g():
    return f

x = "hi"

g()(x)  # equivalent to f(x), since f is what g returns

Notice thay g() returns the function f without actually executing it, which is why there's no parentheses on g's return statement.

Upvotes: 3

Klaus D.
Klaus D.

Reputation: 14369

Both seem to be classes that implement __call__(). Then BatchNormalization() creates an instance and (x) calls .__call__(x) on the instance.

Upvotes: 4

Related Questions